core/iter/traits/iterator.rs
1use super::super::{
2 ArrayChunks, ByRefSized, Chain, Cloned, Copied, Cycle, Enumerate, Filter, FilterMap, FlatMap,
3 Flatten, Fuse, Inspect, Intersperse, IntersperseWith, Map, MapWhile, MapWindows, Peekable,
4 Product, Rev, Scan, Skip, SkipWhile, StepBy, Sum, Take, TakeWhile, TrustedRandomAccessNoCoerce,
5 Zip, try_process,
6};
7use super::TrustedLen;
8use crate::array;
9use crate::cmp::{self, Ordering};
10use crate::num::NonZero;
11use crate::ops::{ChangeOutputType, ControlFlow, FromResidual, Residual, Try};
12
13fn _assert_is_dyn_compatible(_: &dyn Iterator<Item = ()>) {}
14
15/// A trait for dealing with iterators.
16///
17/// This is the main iterator trait. For more about the concept of iterators
18/// generally, please see the [module-level documentation]. In particular, you
19/// may want to know how to [implement `Iterator`][impl].
20///
21/// [module-level documentation]: crate::iter
22/// [impl]: crate::iter#implementing-iterator
23#[stable(feature = "rust1", since = "1.0.0")]
24#[rustc_on_unimplemented(
25 on(
26 Self = "core::ops::range::RangeTo<Idx>",
27 note = "you might have meant to use a bounded `Range`"
28 ),
29 on(
30 Self = "core::ops::range::RangeToInclusive<Idx>",
31 note = "you might have meant to use a bounded `RangeInclusive`"
32 ),
33 label = "`{Self}` is not an iterator",
34 message = "`{Self}` is not an iterator"
35)]
36#[doc(notable_trait)]
37#[lang = "iterator"]
38#[rustc_diagnostic_item = "Iterator"]
39#[must_use = "iterators are lazy and do nothing unless consumed"]
40pub trait Iterator {
41 /// The type of the elements being iterated over.
42 #[rustc_diagnostic_item = "IteratorItem"]
43 #[stable(feature = "rust1", since = "1.0.0")]
44 type Item;
45
46 /// Advances the iterator and returns the next value.
47 ///
48 /// Returns [`None`] when iteration is finished. Individual iterator
49 /// implementations may choose to resume iteration, and so calling `next()`
50 /// again may or may not eventually start returning [`Some(Item)`] again at some
51 /// point.
52 ///
53 /// [`Some(Item)`]: Some
54 ///
55 /// # Examples
56 ///
57 /// ```
58 /// let a = [1, 2, 3];
59 ///
60 /// let mut iter = a.into_iter();
61 ///
62 /// // A call to next() returns the next value...
63 /// assert_eq!(Some(1), iter.next());
64 /// assert_eq!(Some(2), iter.next());
65 /// assert_eq!(Some(3), iter.next());
66 ///
67 /// // ... and then None once it's over.
68 /// assert_eq!(None, iter.next());
69 ///
70 /// // More calls may or may not return `None`. Here, they always will.
71 /// assert_eq!(None, iter.next());
72 /// assert_eq!(None, iter.next());
73 /// ```
74 #[lang = "next"]
75 #[stable(feature = "rust1", since = "1.0.0")]
76 fn next(&mut self) -> Option<Self::Item>;
77
78 /// Advances the iterator and returns an array containing the next `N` values.
79 ///
80 /// If there are not enough elements to fill the array then `Err` is returned
81 /// containing an iterator over the remaining elements.
82 ///
83 /// # Examples
84 ///
85 /// Basic usage:
86 ///
87 /// ```
88 /// #![feature(iter_next_chunk)]
89 ///
90 /// let mut iter = "lorem".chars();
91 ///
92 /// assert_eq!(iter.next_chunk().unwrap(), ['l', 'o']); // N is inferred as 2
93 /// assert_eq!(iter.next_chunk().unwrap(), ['r', 'e', 'm']); // N is inferred as 3
94 /// assert_eq!(iter.next_chunk::<4>().unwrap_err().as_slice(), &[]); // N is explicitly 4
95 /// ```
96 ///
97 /// Split a string and get the first three items.
98 ///
99 /// ```
100 /// #![feature(iter_next_chunk)]
101 ///
102 /// let quote = "not all those who wander are lost";
103 /// let [first, second, third] = quote.split_whitespace().next_chunk().unwrap();
104 /// assert_eq!(first, "not");
105 /// assert_eq!(second, "all");
106 /// assert_eq!(third, "those");
107 /// ```
108 #[inline]
109 #[unstable(feature = "iter_next_chunk", reason = "recently added", issue = "98326")]
110 fn next_chunk<const N: usize>(
111 &mut self,
112 ) -> Result<[Self::Item; N], array::IntoIter<Self::Item, N>>
113 where
114 Self: Sized,
115 {
116 array::iter_next_chunk(self)
117 }
118
119 /// Returns the bounds on the remaining length of the iterator.
120 ///
121 /// Specifically, `size_hint()` returns a tuple where the first element
122 /// is the lower bound, and the second element is the upper bound.
123 ///
124 /// The second half of the tuple that is returned is an <code>[Option]<[usize]></code>.
125 /// A [`None`] here means that either there is no known upper bound, or the
126 /// upper bound is larger than [`usize`].
127 ///
128 /// # Implementation notes
129 ///
130 /// It is not enforced that an iterator implementation yields the declared
131 /// number of elements. A buggy iterator may yield less than the lower bound
132 /// or more than the upper bound of elements.
133 ///
134 /// `size_hint()` is primarily intended to be used for optimizations such as
135 /// reserving space for the elements of the iterator, but must not be
136 /// trusted to e.g., omit bounds checks in unsafe code. An incorrect
137 /// implementation of `size_hint()` should not lead to memory safety
138 /// violations.
139 ///
140 /// That said, the implementation should provide a correct estimation,
141 /// because otherwise it would be a violation of the trait's protocol.
142 ///
143 /// The default implementation returns <code>(0, [None])</code> which is correct for any
144 /// iterator.
145 ///
146 /// # Examples
147 ///
148 /// Basic usage:
149 ///
150 /// ```
151 /// let a = [1, 2, 3];
152 /// let mut iter = a.iter();
153 ///
154 /// assert_eq!((3, Some(3)), iter.size_hint());
155 /// let _ = iter.next();
156 /// assert_eq!((2, Some(2)), iter.size_hint());
157 /// ```
158 ///
159 /// A more complex example:
160 ///
161 /// ```
162 /// // The even numbers in the range of zero to nine.
163 /// let iter = (0..10).filter(|x| x % 2 == 0);
164 ///
165 /// // We might iterate from zero to ten times. Knowing that it's five
166 /// // exactly wouldn't be possible without executing filter().
167 /// assert_eq!((0, Some(10)), iter.size_hint());
168 ///
169 /// // Let's add five more numbers with chain()
170 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
171 ///
172 /// // now both bounds are increased by five
173 /// assert_eq!((5, Some(15)), iter.size_hint());
174 /// ```
175 ///
176 /// Returning `None` for an upper bound:
177 ///
178 /// ```
179 /// // an infinite iterator has no upper bound
180 /// // and the maximum possible lower bound
181 /// let iter = 0..;
182 ///
183 /// assert_eq!((usize::MAX, None), iter.size_hint());
184 /// ```
185 #[inline]
186 #[stable(feature = "rust1", since = "1.0.0")]
187 fn size_hint(&self) -> (usize, Option<usize>) {
188 (0, None)
189 }
190
191 /// Consumes the iterator, counting the number of iterations and returning it.
192 ///
193 /// This method will call [`next`] repeatedly until [`None`] is encountered,
194 /// returning the number of times it saw [`Some`]. Note that [`next`] has to be
195 /// called at least once even if the iterator does not have any elements.
196 ///
197 /// [`next`]: Iterator::next
198 ///
199 /// # Overflow Behavior
200 ///
201 /// The method does no guarding against overflows, so counting elements of
202 /// an iterator with more than [`usize::MAX`] elements either produces the
203 /// wrong result or panics. If overflow checks are enabled, a panic is
204 /// guaranteed.
205 ///
206 /// # Panics
207 ///
208 /// This function might panic if the iterator has more than [`usize::MAX`]
209 /// elements.
210 ///
211 /// # Examples
212 ///
213 /// ```
214 /// let a = [1, 2, 3];
215 /// assert_eq!(a.iter().count(), 3);
216 ///
217 /// let a = [1, 2, 3, 4, 5];
218 /// assert_eq!(a.iter().count(), 5);
219 /// ```
220 #[inline]
221 #[stable(feature = "rust1", since = "1.0.0")]
222 fn count(self) -> usize
223 where
224 Self: Sized,
225 {
226 self.fold(
227 0,
228 #[rustc_inherit_overflow_checks]
229 |count, _| count + 1,
230 )
231 }
232
233 /// Consumes the iterator, returning the last element.
234 ///
235 /// This method will evaluate the iterator until it returns [`None`]. While
236 /// doing so, it keeps track of the current element. After [`None`] is
237 /// returned, `last()` will then return the last element it saw.
238 ///
239 /// # Panics
240 ///
241 /// This function might panic if the iterator is infinite.
242 ///
243 /// # Examples
244 ///
245 /// ```
246 /// let a = [1, 2, 3];
247 /// assert_eq!(a.into_iter().last(), Some(3));
248 ///
249 /// let a = [1, 2, 3, 4, 5];
250 /// assert_eq!(a.into_iter().last(), Some(5));
251 /// ```
252 #[inline]
253 #[stable(feature = "rust1", since = "1.0.0")]
254 fn last(self) -> Option<Self::Item>
255 where
256 Self: Sized,
257 {
258 #[inline]
259 fn some<T>(_: Option<T>, x: T) -> Option<T> {
260 Some(x)
261 }
262
263 self.fold(None, some)
264 }
265
266 /// Advances the iterator by `n` elements.
267 ///
268 /// This method will eagerly skip `n` elements by calling [`next`] up to `n`
269 /// times until [`None`] is encountered.
270 ///
271 /// `advance_by(n)` will return `Ok(())` if the iterator successfully advances by
272 /// `n` elements, or a `Err(NonZero<usize>)` with value `k` if [`None`] is encountered,
273 /// where `k` is remaining number of steps that could not be advanced because the iterator ran out.
274 /// If `self` is empty and `n` is non-zero, then this returns `Err(n)`.
275 /// Otherwise, `k` is always less than `n`.
276 ///
277 /// Calling `advance_by(0)` can do meaningful work, for example [`Flatten`]
278 /// can advance its outer iterator until it finds an inner iterator that is not empty, which
279 /// then often allows it to return a more accurate `size_hint()` than in its initial state.
280 ///
281 /// [`Flatten`]: crate::iter::Flatten
282 /// [`next`]: Iterator::next
283 ///
284 /// # Examples
285 ///
286 /// ```
287 /// #![feature(iter_advance_by)]
288 ///
289 /// use std::num::NonZero;
290 ///
291 /// let a = [1, 2, 3, 4];
292 /// let mut iter = a.into_iter();
293 ///
294 /// assert_eq!(iter.advance_by(2), Ok(()));
295 /// assert_eq!(iter.next(), Some(3));
296 /// assert_eq!(iter.advance_by(0), Ok(()));
297 /// assert_eq!(iter.advance_by(100), Err(NonZero::new(99).unwrap())); // only `4` was skipped
298 /// ```
299 #[inline]
300 #[unstable(feature = "iter_advance_by", reason = "recently added", issue = "77404")]
301 fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
302 /// Helper trait to specialize `advance_by` via `try_fold` for `Sized` iterators.
303 trait SpecAdvanceBy {
304 fn spec_advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>>;
305 }
306
307 impl<I: Iterator + ?Sized> SpecAdvanceBy for I {
308 default fn spec_advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
309 for i in 0..n {
310 if self.next().is_none() {
311 // SAFETY: `i` is always less than `n`.
312 return Err(unsafe { NonZero::new_unchecked(n - i) });
313 }
314 }
315 Ok(())
316 }
317 }
318
319 impl<I: Iterator> SpecAdvanceBy for I {
320 fn spec_advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
321 let Some(n) = NonZero::new(n) else {
322 return Ok(());
323 };
324
325 let res = self.try_fold(n, |n, _| NonZero::new(n.get() - 1));
326
327 match res {
328 None => Ok(()),
329 Some(n) => Err(n),
330 }
331 }
332 }
333
334 self.spec_advance_by(n)
335 }
336
337 /// Returns the `n`th element of the iterator.
338 ///
339 /// Like most indexing operations, the count starts from zero, so `nth(0)`
340 /// returns the first value, `nth(1)` the second, and so on.
341 ///
342 /// Note that all preceding elements, as well as the returned element, will be
343 /// consumed from the iterator. That means that the preceding elements will be
344 /// discarded, and also that calling `nth(0)` multiple times on the same iterator
345 /// will return different elements.
346 ///
347 /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
348 /// iterator.
349 ///
350 /// # Examples
351 ///
352 /// Basic usage:
353 ///
354 /// ```
355 /// let a = [1, 2, 3];
356 /// assert_eq!(a.into_iter().nth(1), Some(2));
357 /// ```
358 ///
359 /// Calling `nth()` multiple times doesn't rewind the iterator:
360 ///
361 /// ```
362 /// let a = [1, 2, 3];
363 ///
364 /// let mut iter = a.into_iter();
365 ///
366 /// assert_eq!(iter.nth(1), Some(2));
367 /// assert_eq!(iter.nth(1), None);
368 /// ```
369 ///
370 /// Returning `None` if there are less than `n + 1` elements:
371 ///
372 /// ```
373 /// let a = [1, 2, 3];
374 /// assert_eq!(a.into_iter().nth(10), None);
375 /// ```
376 #[inline]
377 #[stable(feature = "rust1", since = "1.0.0")]
378 fn nth(&mut self, n: usize) -> Option<Self::Item> {
379 self.advance_by(n).ok()?;
380 self.next()
381 }
382
383 /// Creates an iterator starting at the same point, but stepping by
384 /// the given amount at each iteration.
385 ///
386 /// Note 1: The first element of the iterator will always be returned,
387 /// regardless of the step given.
388 ///
389 /// Note 2: The time at which ignored elements are pulled is not fixed.
390 /// `StepBy` behaves like the sequence `self.next()`, `self.nth(step-1)`,
391 /// `self.nth(step-1)`, …, but is also free to behave like the sequence
392 /// `advance_n_and_return_first(&mut self, step)`,
393 /// `advance_n_and_return_first(&mut self, step)`, …
394 /// Which way is used may change for some iterators for performance reasons.
395 /// The second way will advance the iterator earlier and may consume more items.
396 ///
397 /// `advance_n_and_return_first` is the equivalent of:
398 /// ```
399 /// fn advance_n_and_return_first<I>(iter: &mut I, n: usize) -> Option<I::Item>
400 /// where
401 /// I: Iterator,
402 /// {
403 /// let next = iter.next();
404 /// if n > 1 {
405 /// iter.nth(n - 2);
406 /// }
407 /// next
408 /// }
409 /// ```
410 ///
411 /// # Panics
412 ///
413 /// The method will panic if the given step is `0`.
414 ///
415 /// # Examples
416 ///
417 /// ```
418 /// let a = [0, 1, 2, 3, 4, 5];
419 /// let mut iter = a.into_iter().step_by(2);
420 ///
421 /// assert_eq!(iter.next(), Some(0));
422 /// assert_eq!(iter.next(), Some(2));
423 /// assert_eq!(iter.next(), Some(4));
424 /// assert_eq!(iter.next(), None);
425 /// ```
426 #[inline]
427 #[stable(feature = "iterator_step_by", since = "1.28.0")]
428 fn step_by(self, step: usize) -> StepBy<Self>
429 where
430 Self: Sized,
431 {
432 StepBy::new(self, step)
433 }
434
435 /// Takes two iterators and creates a new iterator over both in sequence.
436 ///
437 /// `chain()` will return a new iterator which will first iterate over
438 /// values from the first iterator and then over values from the second
439 /// iterator.
440 ///
441 /// In other words, it links two iterators together, in a chain. 🔗
442 ///
443 /// [`once`] is commonly used to adapt a single value into a chain of
444 /// other kinds of iteration.
445 ///
446 /// # Examples
447 ///
448 /// Basic usage:
449 ///
450 /// ```
451 /// let s1 = "abc".chars();
452 /// let s2 = "def".chars();
453 ///
454 /// let mut iter = s1.chain(s2);
455 ///
456 /// assert_eq!(iter.next(), Some('a'));
457 /// assert_eq!(iter.next(), Some('b'));
458 /// assert_eq!(iter.next(), Some('c'));
459 /// assert_eq!(iter.next(), Some('d'));
460 /// assert_eq!(iter.next(), Some('e'));
461 /// assert_eq!(iter.next(), Some('f'));
462 /// assert_eq!(iter.next(), None);
463 /// ```
464 ///
465 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
466 /// anything that can be converted into an [`Iterator`], not just an
467 /// [`Iterator`] itself. For example, arrays (`[T]`) implement
468 /// [`IntoIterator`], and so can be passed to `chain()` directly:
469 ///
470 /// ```
471 /// let a1 = [1, 2, 3];
472 /// let a2 = [4, 5, 6];
473 ///
474 /// let mut iter = a1.into_iter().chain(a2);
475 ///
476 /// assert_eq!(iter.next(), Some(1));
477 /// assert_eq!(iter.next(), Some(2));
478 /// assert_eq!(iter.next(), Some(3));
479 /// assert_eq!(iter.next(), Some(4));
480 /// assert_eq!(iter.next(), Some(5));
481 /// assert_eq!(iter.next(), Some(6));
482 /// assert_eq!(iter.next(), None);
483 /// ```
484 ///
485 /// If you work with Windows API, you may wish to convert [`OsStr`] to `Vec<u16>`:
486 ///
487 /// ```
488 /// #[cfg(windows)]
489 /// fn os_str_to_utf16(s: &std::ffi::OsStr) -> Vec<u16> {
490 /// use std::os::windows::ffi::OsStrExt;
491 /// s.encode_wide().chain(std::iter::once(0)).collect()
492 /// }
493 /// ```
494 ///
495 /// [`once`]: crate::iter::once
496 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
497 #[inline]
498 #[stable(feature = "rust1", since = "1.0.0")]
499 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter>
500 where
501 Self: Sized,
502 U: IntoIterator<Item = Self::Item>,
503 {
504 Chain::new(self, other.into_iter())
505 }
506
507 /// 'Zips up' two iterators into a single iterator of pairs.
508 ///
509 /// `zip()` returns a new iterator that will iterate over two other
510 /// iterators, returning a tuple where the first element comes from the
511 /// first iterator, and the second element comes from the second iterator.
512 ///
513 /// In other words, it zips two iterators together, into a single one.
514 ///
515 /// If either iterator returns [`None`], [`next`] from the zipped iterator
516 /// will return [`None`].
517 /// If the zipped iterator has no more elements to return then each further attempt to advance
518 /// it will first try to advance the first iterator at most one time and if it still yielded an item
519 /// try to advance the second iterator at most one time.
520 ///
521 /// To 'undo' the result of zipping up two iterators, see [`unzip`].
522 ///
523 /// [`unzip`]: Iterator::unzip
524 ///
525 /// # Examples
526 ///
527 /// Basic usage:
528 ///
529 /// ```
530 /// let s1 = "abc".chars();
531 /// let s2 = "def".chars();
532 ///
533 /// let mut iter = s1.zip(s2);
534 ///
535 /// assert_eq!(iter.next(), Some(('a', 'd')));
536 /// assert_eq!(iter.next(), Some(('b', 'e')));
537 /// assert_eq!(iter.next(), Some(('c', 'f')));
538 /// assert_eq!(iter.next(), None);
539 /// ```
540 ///
541 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
542 /// anything that can be converted into an [`Iterator`], not just an
543 /// [`Iterator`] itself. For example, arrays (`[T]`) implement
544 /// [`IntoIterator`], and so can be passed to `zip()` directly:
545 ///
546 /// ```
547 /// let a1 = [1, 2, 3];
548 /// let a2 = [4, 5, 6];
549 ///
550 /// let mut iter = a1.into_iter().zip(a2);
551 ///
552 /// assert_eq!(iter.next(), Some((1, 4)));
553 /// assert_eq!(iter.next(), Some((2, 5)));
554 /// assert_eq!(iter.next(), Some((3, 6)));
555 /// assert_eq!(iter.next(), None);
556 /// ```
557 ///
558 /// `zip()` is often used to zip an infinite iterator to a finite one.
559 /// This works because the finite iterator will eventually return [`None`],
560 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
561 ///
562 /// ```
563 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
564 ///
565 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
566 ///
567 /// assert_eq!((0, 'f'), enumerate[0]);
568 /// assert_eq!((0, 'f'), zipper[0]);
569 ///
570 /// assert_eq!((1, 'o'), enumerate[1]);
571 /// assert_eq!((1, 'o'), zipper[1]);
572 ///
573 /// assert_eq!((2, 'o'), enumerate[2]);
574 /// assert_eq!((2, 'o'), zipper[2]);
575 /// ```
576 ///
577 /// If both iterators have roughly equivalent syntax, it may be more readable to use [`zip`]:
578 ///
579 /// ```
580 /// use std::iter::zip;
581 ///
582 /// let a = [1, 2, 3];
583 /// let b = [2, 3, 4];
584 ///
585 /// let mut zipped = zip(
586 /// a.into_iter().map(|x| x * 2).skip(1),
587 /// b.into_iter().map(|x| x * 2).skip(1),
588 /// );
589 ///
590 /// assert_eq!(zipped.next(), Some((4, 6)));
591 /// assert_eq!(zipped.next(), Some((6, 8)));
592 /// assert_eq!(zipped.next(), None);
593 /// ```
594 ///
595 /// compared to:
596 ///
597 /// ```
598 /// # let a = [1, 2, 3];
599 /// # let b = [2, 3, 4];
600 /// #
601 /// let mut zipped = a
602 /// .into_iter()
603 /// .map(|x| x * 2)
604 /// .skip(1)
605 /// .zip(b.into_iter().map(|x| x * 2).skip(1));
606 /// #
607 /// # assert_eq!(zipped.next(), Some((4, 6)));
608 /// # assert_eq!(zipped.next(), Some((6, 8)));
609 /// # assert_eq!(zipped.next(), None);
610 /// ```
611 ///
612 /// [`enumerate`]: Iterator::enumerate
613 /// [`next`]: Iterator::next
614 /// [`zip`]: crate::iter::zip
615 #[inline]
616 #[stable(feature = "rust1", since = "1.0.0")]
617 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter>
618 where
619 Self: Sized,
620 U: IntoIterator,
621 {
622 Zip::new(self, other.into_iter())
623 }
624
625 /// Creates a new iterator which places a copy of `separator` between adjacent
626 /// items of the original iterator.
627 ///
628 /// In case `separator` does not implement [`Clone`] or needs to be
629 /// computed every time, use [`intersperse_with`].
630 ///
631 /// # Examples
632 ///
633 /// Basic usage:
634 ///
635 /// ```
636 /// #![feature(iter_intersperse)]
637 ///
638 /// let mut a = [0, 1, 2].into_iter().intersperse(100);
639 /// assert_eq!(a.next(), Some(0)); // The first element from `a`.
640 /// assert_eq!(a.next(), Some(100)); // The separator.
641 /// assert_eq!(a.next(), Some(1)); // The next element from `a`.
642 /// assert_eq!(a.next(), Some(100)); // The separator.
643 /// assert_eq!(a.next(), Some(2)); // The last element from `a`.
644 /// assert_eq!(a.next(), None); // The iterator is finished.
645 /// ```
646 ///
647 /// `intersperse` can be very useful to join an iterator's items using a common element:
648 /// ```
649 /// #![feature(iter_intersperse)]
650 ///
651 /// let words = ["Hello", "World", "!"];
652 /// let hello: String = words.into_iter().intersperse(" ").collect();
653 /// assert_eq!(hello, "Hello World !");
654 /// ```
655 ///
656 /// [`Clone`]: crate::clone::Clone
657 /// [`intersperse_with`]: Iterator::intersperse_with
658 #[inline]
659 #[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")]
660 fn intersperse(self, separator: Self::Item) -> Intersperse<Self>
661 where
662 Self: Sized,
663 Self::Item: Clone,
664 {
665 Intersperse::new(self, separator)
666 }
667
668 /// Creates a new iterator which places an item generated by `separator`
669 /// between adjacent items of the original iterator.
670 ///
671 /// The closure will be called exactly once each time an item is placed
672 /// between two adjacent items from the underlying iterator; specifically,
673 /// the closure is not called if the underlying iterator yields less than
674 /// two items and after the last item is yielded.
675 ///
676 /// If the iterator's item implements [`Clone`], it may be easier to use
677 /// [`intersperse`].
678 ///
679 /// # Examples
680 ///
681 /// Basic usage:
682 ///
683 /// ```
684 /// #![feature(iter_intersperse)]
685 ///
686 /// #[derive(PartialEq, Debug)]
687 /// struct NotClone(usize);
688 ///
689 /// let v = [NotClone(0), NotClone(1), NotClone(2)];
690 /// let mut it = v.into_iter().intersperse_with(|| NotClone(99));
691 ///
692 /// assert_eq!(it.next(), Some(NotClone(0))); // The first element from `v`.
693 /// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
694 /// assert_eq!(it.next(), Some(NotClone(1))); // The next element from `v`.
695 /// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
696 /// assert_eq!(it.next(), Some(NotClone(2))); // The last element from `v`.
697 /// assert_eq!(it.next(), None); // The iterator is finished.
698 /// ```
699 ///
700 /// `intersperse_with` can be used in situations where the separator needs
701 /// to be computed:
702 /// ```
703 /// #![feature(iter_intersperse)]
704 ///
705 /// let src = ["Hello", "to", "all", "people", "!!"].iter().copied();
706 ///
707 /// // The closure mutably borrows its context to generate an item.
708 /// let mut happy_emojis = [" ❤️ ", " 😀 "].into_iter();
709 /// let separator = || happy_emojis.next().unwrap_or(" 🦀 ");
710 ///
711 /// let result = src.intersperse_with(separator).collect::<String>();
712 /// assert_eq!(result, "Hello ❤️ to 😀 all 🦀 people 🦀 !!");
713 /// ```
714 /// [`Clone`]: crate::clone::Clone
715 /// [`intersperse`]: Iterator::intersperse
716 #[inline]
717 #[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")]
718 fn intersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G>
719 where
720 Self: Sized,
721 G: FnMut() -> Self::Item,
722 {
723 IntersperseWith::new(self, separator)
724 }
725
726 /// Takes a closure and creates an iterator which calls that closure on each
727 /// element.
728 ///
729 /// `map()` transforms one iterator into another, by means of its argument:
730 /// something that implements [`FnMut`]. It produces a new iterator which
731 /// calls this closure on each element of the original iterator.
732 ///
733 /// If you are good at thinking in types, you can think of `map()` like this:
734 /// If you have an iterator that gives you elements of some type `A`, and
735 /// you want an iterator of some other type `B`, you can use `map()`,
736 /// passing a closure that takes an `A` and returns a `B`.
737 ///
738 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
739 /// lazy, it is best used when you're already working with other iterators.
740 /// If you're doing some sort of looping for a side effect, it's considered
741 /// more idiomatic to use [`for`] than `map()`.
742 ///
743 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
744 ///
745 /// # Examples
746 ///
747 /// Basic usage:
748 ///
749 /// ```
750 /// let a = [1, 2, 3];
751 ///
752 /// let mut iter = a.iter().map(|x| 2 * x);
753 ///
754 /// assert_eq!(iter.next(), Some(2));
755 /// assert_eq!(iter.next(), Some(4));
756 /// assert_eq!(iter.next(), Some(6));
757 /// assert_eq!(iter.next(), None);
758 /// ```
759 ///
760 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
761 ///
762 /// ```
763 /// # #![allow(unused_must_use)]
764 /// // don't do this:
765 /// (0..5).map(|x| println!("{x}"));
766 ///
767 /// // it won't even execute, as it is lazy. Rust will warn you about this.
768 ///
769 /// // Instead, use a for-loop:
770 /// for x in 0..5 {
771 /// println!("{x}");
772 /// }
773 /// ```
774 #[rustc_diagnostic_item = "IteratorMap"]
775 #[inline]
776 #[stable(feature = "rust1", since = "1.0.0")]
777 fn map<B, F>(self, f: F) -> Map<Self, F>
778 where
779 Self: Sized,
780 F: FnMut(Self::Item) -> B,
781 {
782 Map::new(self, f)
783 }
784
785 /// Calls a closure on each element of an iterator.
786 ///
787 /// This is equivalent to using a [`for`] loop on the iterator, although
788 /// `break` and `continue` are not possible from a closure. It's generally
789 /// more idiomatic to use a `for` loop, but `for_each` may be more legible
790 /// when processing items at the end of longer iterator chains. In some
791 /// cases `for_each` may also be faster than a loop, because it will use
792 /// internal iteration on adapters like `Chain`.
793 ///
794 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
795 ///
796 /// # Examples
797 ///
798 /// Basic usage:
799 ///
800 /// ```
801 /// use std::sync::mpsc::channel;
802 ///
803 /// let (tx, rx) = channel();
804 /// (0..5).map(|x| x * 2 + 1)
805 /// .for_each(move |x| tx.send(x).unwrap());
806 ///
807 /// let v: Vec<_> = rx.iter().collect();
808 /// assert_eq!(v, vec![1, 3, 5, 7, 9]);
809 /// ```
810 ///
811 /// For such a small example, a `for` loop may be cleaner, but `for_each`
812 /// might be preferable to keep a functional style with longer iterators:
813 ///
814 /// ```
815 /// (0..5).flat_map(|x| (x * 100)..(x * 110))
816 /// .enumerate()
817 /// .filter(|&(i, x)| (i + x) % 3 == 0)
818 /// .for_each(|(i, x)| println!("{i}:{x}"));
819 /// ```
820 #[inline]
821 #[stable(feature = "iterator_for_each", since = "1.21.0")]
822 fn for_each<F>(self, f: F)
823 where
824 Self: Sized,
825 F: FnMut(Self::Item),
826 {
827 #[inline]
828 fn call<T>(mut f: impl FnMut(T)) -> impl FnMut((), T) {
829 move |(), item| f(item)
830 }
831
832 self.fold((), call(f));
833 }
834
835 /// Creates an iterator which uses a closure to determine if an element
836 /// should be yielded.
837 ///
838 /// Given an element the closure must return `true` or `false`. The returned
839 /// iterator will yield only the elements for which the closure returns
840 /// `true`.
841 ///
842 /// # Examples
843 ///
844 /// Basic usage:
845 ///
846 /// ```
847 /// let a = [0i32, 1, 2];
848 ///
849 /// let mut iter = a.into_iter().filter(|x| x.is_positive());
850 ///
851 /// assert_eq!(iter.next(), Some(1));
852 /// assert_eq!(iter.next(), Some(2));
853 /// assert_eq!(iter.next(), None);
854 /// ```
855 ///
856 /// Because the closure passed to `filter()` takes a reference, and many
857 /// iterators iterate over references, this leads to a possibly confusing
858 /// situation, where the type of the closure is a double reference:
859 ///
860 /// ```
861 /// let s = &[0, 1, 2];
862 ///
863 /// let mut iter = s.iter().filter(|x| **x > 1); // needs two *s!
864 ///
865 /// assert_eq!(iter.next(), Some(&2));
866 /// assert_eq!(iter.next(), None);
867 /// ```
868 ///
869 /// It's common to instead use destructuring on the argument to strip away one:
870 ///
871 /// ```
872 /// let s = &[0, 1, 2];
873 ///
874 /// let mut iter = s.iter().filter(|&x| *x > 1); // both & and *
875 ///
876 /// assert_eq!(iter.next(), Some(&2));
877 /// assert_eq!(iter.next(), None);
878 /// ```
879 ///
880 /// or both:
881 ///
882 /// ```
883 /// let s = &[0, 1, 2];
884 ///
885 /// let mut iter = s.iter().filter(|&&x| x > 1); // two &s
886 ///
887 /// assert_eq!(iter.next(), Some(&2));
888 /// assert_eq!(iter.next(), None);
889 /// ```
890 ///
891 /// of these layers.
892 ///
893 /// Note that `iter.filter(f).next()` is equivalent to `iter.find(f)`.
894 #[inline]
895 #[stable(feature = "rust1", since = "1.0.0")]
896 #[rustc_diagnostic_item = "iter_filter"]
897 fn filter<P>(self, predicate: P) -> Filter<Self, P>
898 where
899 Self: Sized,
900 P: FnMut(&Self::Item) -> bool,
901 {
902 Filter::new(self, predicate)
903 }
904
905 /// Creates an iterator that both filters and maps.
906 ///
907 /// The returned iterator yields only the `value`s for which the supplied
908 /// closure returns `Some(value)`.
909 ///
910 /// `filter_map` can be used to make chains of [`filter`] and [`map`] more
911 /// concise. The example below shows how a `map().filter().map()` can be
912 /// shortened to a single call to `filter_map`.
913 ///
914 /// [`filter`]: Iterator::filter
915 /// [`map`]: Iterator::map
916 ///
917 /// # Examples
918 ///
919 /// Basic usage:
920 ///
921 /// ```
922 /// let a = ["1", "two", "NaN", "four", "5"];
923 ///
924 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
925 ///
926 /// assert_eq!(iter.next(), Some(1));
927 /// assert_eq!(iter.next(), Some(5));
928 /// assert_eq!(iter.next(), None);
929 /// ```
930 ///
931 /// Here's the same example, but with [`filter`] and [`map`]:
932 ///
933 /// ```
934 /// let a = ["1", "two", "NaN", "four", "5"];
935 /// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());
936 /// assert_eq!(iter.next(), Some(1));
937 /// assert_eq!(iter.next(), Some(5));
938 /// assert_eq!(iter.next(), None);
939 /// ```
940 #[inline]
941 #[stable(feature = "rust1", since = "1.0.0")]
942 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>
943 where
944 Self: Sized,
945 F: FnMut(Self::Item) -> Option<B>,
946 {
947 FilterMap::new(self, f)
948 }
949
950 /// Creates an iterator which gives the current iteration count as well as
951 /// the next value.
952 ///
953 /// The iterator returned yields pairs `(i, val)`, where `i` is the
954 /// current index of iteration and `val` is the value returned by the
955 /// iterator.
956 ///
957 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
958 /// different sized integer, the [`zip`] function provides similar
959 /// functionality.
960 ///
961 /// # Overflow Behavior
962 ///
963 /// The method does no guarding against overflows, so enumerating more than
964 /// [`usize::MAX`] elements either produces the wrong result or panics. If
965 /// overflow checks are enabled, a panic is guaranteed.
966 ///
967 /// # Panics
968 ///
969 /// The returned iterator might panic if the to-be-returned index would
970 /// overflow a [`usize`].
971 ///
972 /// [`zip`]: Iterator::zip
973 ///
974 /// # Examples
975 ///
976 /// ```
977 /// let a = ['a', 'b', 'c'];
978 ///
979 /// let mut iter = a.into_iter().enumerate();
980 ///
981 /// assert_eq!(iter.next(), Some((0, 'a')));
982 /// assert_eq!(iter.next(), Some((1, 'b')));
983 /// assert_eq!(iter.next(), Some((2, 'c')));
984 /// assert_eq!(iter.next(), None);
985 /// ```
986 #[inline]
987 #[stable(feature = "rust1", since = "1.0.0")]
988 #[rustc_diagnostic_item = "enumerate_method"]
989 fn enumerate(self) -> Enumerate<Self>
990 where
991 Self: Sized,
992 {
993 Enumerate::new(self)
994 }
995
996 /// Creates an iterator which can use the [`peek`] and [`peek_mut`] methods
997 /// to look at the next element of the iterator without consuming it. See
998 /// their documentation for more information.
999 ///
1000 /// Note that the underlying iterator is still advanced when [`peek`] or
1001 /// [`peek_mut`] are called for the first time: In order to retrieve the
1002 /// next element, [`next`] is called on the underlying iterator, hence any
1003 /// side effects (i.e. anything other than fetching the next value) of
1004 /// the [`next`] method will occur.
1005 ///
1006 ///
1007 /// # Examples
1008 ///
1009 /// Basic usage:
1010 ///
1011 /// ```
1012 /// let xs = [1, 2, 3];
1013 ///
1014 /// let mut iter = xs.into_iter().peekable();
1015 ///
1016 /// // peek() lets us see into the future
1017 /// assert_eq!(iter.peek(), Some(&1));
1018 /// assert_eq!(iter.next(), Some(1));
1019 ///
1020 /// assert_eq!(iter.next(), Some(2));
1021 ///
1022 /// // we can peek() multiple times, the iterator won't advance
1023 /// assert_eq!(iter.peek(), Some(&3));
1024 /// assert_eq!(iter.peek(), Some(&3));
1025 ///
1026 /// assert_eq!(iter.next(), Some(3));
1027 ///
1028 /// // after the iterator is finished, so is peek()
1029 /// assert_eq!(iter.peek(), None);
1030 /// assert_eq!(iter.next(), None);
1031 /// ```
1032 ///
1033 /// Using [`peek_mut`] to mutate the next item without advancing the
1034 /// iterator:
1035 ///
1036 /// ```
1037 /// let xs = [1, 2, 3];
1038 ///
1039 /// let mut iter = xs.into_iter().peekable();
1040 ///
1041 /// // `peek_mut()` lets us see into the future
1042 /// assert_eq!(iter.peek_mut(), Some(&mut 1));
1043 /// assert_eq!(iter.peek_mut(), Some(&mut 1));
1044 /// assert_eq!(iter.next(), Some(1));
1045 ///
1046 /// if let Some(p) = iter.peek_mut() {
1047 /// assert_eq!(*p, 2);
1048 /// // put a value into the iterator
1049 /// *p = 1000;
1050 /// }
1051 ///
1052 /// // The value reappears as the iterator continues
1053 /// assert_eq!(iter.collect::<Vec<_>>(), vec![1000, 3]);
1054 /// ```
1055 /// [`peek`]: Peekable::peek
1056 /// [`peek_mut`]: Peekable::peek_mut
1057 /// [`next`]: Iterator::next
1058 #[inline]
1059 #[stable(feature = "rust1", since = "1.0.0")]
1060 fn peekable(self) -> Peekable<Self>
1061 where
1062 Self: Sized,
1063 {
1064 Peekable::new(self)
1065 }
1066
1067 /// Creates an iterator that [`skip`]s elements based on a predicate.
1068 ///
1069 /// [`skip`]: Iterator::skip
1070 ///
1071 /// `skip_while()` takes a closure as an argument. It will call this
1072 /// closure on each element of the iterator, and ignore elements
1073 /// until it returns `false`.
1074 ///
1075 /// After `false` is returned, `skip_while()`'s job is over, and the
1076 /// rest of the elements are yielded.
1077 ///
1078 /// # Examples
1079 ///
1080 /// Basic usage:
1081 ///
1082 /// ```
1083 /// let a = [-1i32, 0, 1];
1084 ///
1085 /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
1086 ///
1087 /// assert_eq!(iter.next(), Some(0));
1088 /// assert_eq!(iter.next(), Some(1));
1089 /// assert_eq!(iter.next(), None);
1090 /// ```
1091 ///
1092 /// Because the closure passed to `skip_while()` takes a reference, and many
1093 /// iterators iterate over references, this leads to a possibly confusing
1094 /// situation, where the type of the closure argument is a double reference:
1095 ///
1096 /// ```
1097 /// let s = &[-1, 0, 1];
1098 ///
1099 /// let mut iter = s.iter().skip_while(|x| **x < 0); // need two *s!
1100 ///
1101 /// assert_eq!(iter.next(), Some(&0));
1102 /// assert_eq!(iter.next(), Some(&1));
1103 /// assert_eq!(iter.next(), None);
1104 /// ```
1105 ///
1106 /// Stopping after an initial `false`:
1107 ///
1108 /// ```
1109 /// let a = [-1, 0, 1, -2];
1110 ///
1111 /// let mut iter = a.into_iter().skip_while(|&x| x < 0);
1112 ///
1113 /// assert_eq!(iter.next(), Some(0));
1114 /// assert_eq!(iter.next(), Some(1));
1115 ///
1116 /// // while this would have been false, since we already got a false,
1117 /// // skip_while() isn't used any more
1118 /// assert_eq!(iter.next(), Some(-2));
1119 ///
1120 /// assert_eq!(iter.next(), None);
1121 /// ```
1122 #[inline]
1123 #[doc(alias = "drop_while")]
1124 #[stable(feature = "rust1", since = "1.0.0")]
1125 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
1126 where
1127 Self: Sized,
1128 P: FnMut(&Self::Item) -> bool,
1129 {
1130 SkipWhile::new(self, predicate)
1131 }
1132
1133 /// Creates an iterator that yields elements based on a predicate.
1134 ///
1135 /// `take_while()` takes a closure as an argument. It will call this
1136 /// closure on each element of the iterator, and yield elements
1137 /// while it returns `true`.
1138 ///
1139 /// After `false` is returned, `take_while()`'s job is over, and the
1140 /// rest of the elements are ignored.
1141 ///
1142 /// # Examples
1143 ///
1144 /// Basic usage:
1145 ///
1146 /// ```
1147 /// let a = [-1i32, 0, 1];
1148 ///
1149 /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
1150 ///
1151 /// assert_eq!(iter.next(), Some(-1));
1152 /// assert_eq!(iter.next(), None);
1153 /// ```
1154 ///
1155 /// Because the closure passed to `take_while()` takes a reference, and many
1156 /// iterators iterate over references, this leads to a possibly confusing
1157 /// situation, where the type of the closure is a double reference:
1158 ///
1159 /// ```
1160 /// let s = &[-1, 0, 1];
1161 ///
1162 /// let mut iter = s.iter().take_while(|x| **x < 0); // need two *s!
1163 ///
1164 /// assert_eq!(iter.next(), Some(&-1));
1165 /// assert_eq!(iter.next(), None);
1166 /// ```
1167 ///
1168 /// Stopping after an initial `false`:
1169 ///
1170 /// ```
1171 /// let a = [-1, 0, 1, -2];
1172 ///
1173 /// let mut iter = a.into_iter().take_while(|&x| x < 0);
1174 ///
1175 /// assert_eq!(iter.next(), Some(-1));
1176 ///
1177 /// // We have more elements that are less than zero, but since we already
1178 /// // got a false, take_while() ignores the remaining elements.
1179 /// assert_eq!(iter.next(), None);
1180 /// ```
1181 ///
1182 /// Because `take_while()` needs to look at the value in order to see if it
1183 /// should be included or not, consuming iterators will see that it is
1184 /// removed:
1185 ///
1186 /// ```
1187 /// let a = [1, 2, 3, 4];
1188 /// let mut iter = a.into_iter();
1189 ///
1190 /// let result: Vec<i32> = iter.by_ref().take_while(|&n| n != 3).collect();
1191 ///
1192 /// assert_eq!(result, [1, 2]);
1193 ///
1194 /// let result: Vec<i32> = iter.collect();
1195 ///
1196 /// assert_eq!(result, [4]);
1197 /// ```
1198 ///
1199 /// The `3` is no longer there, because it was consumed in order to see if
1200 /// the iteration should stop, but wasn't placed back into the iterator.
1201 #[inline]
1202 #[stable(feature = "rust1", since = "1.0.0")]
1203 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
1204 where
1205 Self: Sized,
1206 P: FnMut(&Self::Item) -> bool,
1207 {
1208 TakeWhile::new(self, predicate)
1209 }
1210
1211 /// Creates an iterator that both yields elements based on a predicate and maps.
1212 ///
1213 /// `map_while()` takes a closure as an argument. It will call this
1214 /// closure on each element of the iterator, and yield elements
1215 /// while it returns [`Some(_)`][`Some`].
1216 ///
1217 /// # Examples
1218 ///
1219 /// Basic usage:
1220 ///
1221 /// ```
1222 /// let a = [-1i32, 4, 0, 1];
1223 ///
1224 /// let mut iter = a.into_iter().map_while(|x| 16i32.checked_div(x));
1225 ///
1226 /// assert_eq!(iter.next(), Some(-16));
1227 /// assert_eq!(iter.next(), Some(4));
1228 /// assert_eq!(iter.next(), None);
1229 /// ```
1230 ///
1231 /// Here's the same example, but with [`take_while`] and [`map`]:
1232 ///
1233 /// [`take_while`]: Iterator::take_while
1234 /// [`map`]: Iterator::map
1235 ///
1236 /// ```
1237 /// let a = [-1i32, 4, 0, 1];
1238 ///
1239 /// let mut iter = a.into_iter()
1240 /// .map(|x| 16i32.checked_div(x))
1241 /// .take_while(|x| x.is_some())
1242 /// .map(|x| x.unwrap());
1243 ///
1244 /// assert_eq!(iter.next(), Some(-16));
1245 /// assert_eq!(iter.next(), Some(4));
1246 /// assert_eq!(iter.next(), None);
1247 /// ```
1248 ///
1249 /// Stopping after an initial [`None`]:
1250 ///
1251 /// ```
1252 /// let a = [0, 1, 2, -3, 4, 5, -6];
1253 ///
1254 /// let iter = a.into_iter().map_while(|x| u32::try_from(x).ok());
1255 /// let vec: Vec<_> = iter.collect();
1256 ///
1257 /// // We have more elements that could fit in u32 (such as 4, 5), but `map_while` returned `None` for `-3`
1258 /// // (as the `predicate` returned `None`) and `collect` stops at the first `None` encountered.
1259 /// assert_eq!(vec, [0, 1, 2]);
1260 /// ```
1261 ///
1262 /// Because `map_while()` needs to look at the value in order to see if it
1263 /// should be included or not, consuming iterators will see that it is
1264 /// removed:
1265 ///
1266 /// ```
1267 /// let a = [1, 2, -3, 4];
1268 /// let mut iter = a.into_iter();
1269 ///
1270 /// let result: Vec<u32> = iter.by_ref()
1271 /// .map_while(|n| u32::try_from(n).ok())
1272 /// .collect();
1273 ///
1274 /// assert_eq!(result, [1, 2]);
1275 ///
1276 /// let result: Vec<i32> = iter.collect();
1277 ///
1278 /// assert_eq!(result, [4]);
1279 /// ```
1280 ///
1281 /// The `-3` is no longer there, because it was consumed in order to see if
1282 /// the iteration should stop, but wasn't placed back into the iterator.
1283 ///
1284 /// Note that unlike [`take_while`] this iterator is **not** fused.
1285 /// It is also not specified what this iterator returns after the first [`None`] is returned.
1286 /// If you need a fused iterator, use [`fuse`].
1287 ///
1288 /// [`fuse`]: Iterator::fuse
1289 #[inline]
1290 #[stable(feature = "iter_map_while", since = "1.57.0")]
1291 fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>
1292 where
1293 Self: Sized,
1294 P: FnMut(Self::Item) -> Option<B>,
1295 {
1296 MapWhile::new(self, predicate)
1297 }
1298
1299 /// Creates an iterator that skips the first `n` elements.
1300 ///
1301 /// `skip(n)` skips elements until `n` elements are skipped or the end of the
1302 /// iterator is reached (whichever happens first). After that, all the remaining
1303 /// elements are yielded. In particular, if the original iterator is too short,
1304 /// then the returned iterator is empty.
1305 ///
1306 /// Rather than overriding this method directly, instead override the `nth` method.
1307 ///
1308 /// # Examples
1309 ///
1310 /// ```
1311 /// let a = [1, 2, 3];
1312 ///
1313 /// let mut iter = a.into_iter().skip(2);
1314 ///
1315 /// assert_eq!(iter.next(), Some(3));
1316 /// assert_eq!(iter.next(), None);
1317 /// ```
1318 #[inline]
1319 #[stable(feature = "rust1", since = "1.0.0")]
1320 fn skip(self, n: usize) -> Skip<Self>
1321 where
1322 Self: Sized,
1323 {
1324 Skip::new(self, n)
1325 }
1326
1327 /// Creates an iterator that yields the first `n` elements, or fewer
1328 /// if the underlying iterator ends sooner.
1329 ///
1330 /// `take(n)` yields elements until `n` elements are yielded or the end of
1331 /// the iterator is reached (whichever happens first).
1332 /// The returned iterator is a prefix of length `n` if the original iterator
1333 /// contains at least `n` elements, otherwise it contains all of the
1334 /// (fewer than `n`) elements of the original iterator.
1335 ///
1336 /// # Examples
1337 ///
1338 /// Basic usage:
1339 ///
1340 /// ```
1341 /// let a = [1, 2, 3];
1342 ///
1343 /// let mut iter = a.into_iter().take(2);
1344 ///
1345 /// assert_eq!(iter.next(), Some(1));
1346 /// assert_eq!(iter.next(), Some(2));
1347 /// assert_eq!(iter.next(), None);
1348 /// ```
1349 ///
1350 /// `take()` is often used with an infinite iterator, to make it finite:
1351 ///
1352 /// ```
1353 /// let mut iter = (0..).take(3);
1354 ///
1355 /// assert_eq!(iter.next(), Some(0));
1356 /// assert_eq!(iter.next(), Some(1));
1357 /// assert_eq!(iter.next(), Some(2));
1358 /// assert_eq!(iter.next(), None);
1359 /// ```
1360 ///
1361 /// If less than `n` elements are available,
1362 /// `take` will limit itself to the size of the underlying iterator:
1363 ///
1364 /// ```
1365 /// let v = [1, 2];
1366 /// let mut iter = v.into_iter().take(5);
1367 /// assert_eq!(iter.next(), Some(1));
1368 /// assert_eq!(iter.next(), Some(2));
1369 /// assert_eq!(iter.next(), None);
1370 /// ```
1371 ///
1372 /// Use [`by_ref`] to take from the iterator without consuming it, and then
1373 /// continue using the original iterator:
1374 ///
1375 /// ```
1376 /// let mut words = ["hello", "world", "of", "Rust"].into_iter();
1377 ///
1378 /// // Take the first two words.
1379 /// let hello_world: Vec<_> = words.by_ref().take(2).collect();
1380 /// assert_eq!(hello_world, vec!["hello", "world"]);
1381 ///
1382 /// // Collect the rest of the words.
1383 /// // We can only do this because we used `by_ref` earlier.
1384 /// let of_rust: Vec<_> = words.collect();
1385 /// assert_eq!(of_rust, vec!["of", "Rust"]);
1386 /// ```
1387 ///
1388 /// [`by_ref`]: Iterator::by_ref
1389 #[doc(alias = "limit")]
1390 #[inline]
1391 #[stable(feature = "rust1", since = "1.0.0")]
1392 fn take(self, n: usize) -> Take<Self>
1393 where
1394 Self: Sized,
1395 {
1396 Take::new(self, n)
1397 }
1398
1399 /// An iterator adapter which, like [`fold`], holds internal state, but
1400 /// unlike [`fold`], produces a new iterator.
1401 ///
1402 /// [`fold`]: Iterator::fold
1403 ///
1404 /// `scan()` takes two arguments: an initial value which seeds the internal
1405 /// state, and a closure with two arguments, the first being a mutable
1406 /// reference to the internal state and the second an iterator element.
1407 /// The closure can assign to the internal state to share state between
1408 /// iterations.
1409 ///
1410 /// On iteration, the closure will be applied to each element of the
1411 /// iterator and the return value from the closure, an [`Option`], is
1412 /// returned by the `next` method. Thus the closure can return
1413 /// `Some(value)` to yield `value`, or `None` to end the iteration.
1414 ///
1415 /// # Examples
1416 ///
1417 /// ```
1418 /// let a = [1, 2, 3, 4];
1419 ///
1420 /// let mut iter = a.into_iter().scan(1, |state, x| {
1421 /// // each iteration, we'll multiply the state by the element ...
1422 /// *state = *state * x;
1423 ///
1424 /// // ... and terminate if the state exceeds 6
1425 /// if *state > 6 {
1426 /// return None;
1427 /// }
1428 /// // ... else yield the negation of the state
1429 /// Some(-*state)
1430 /// });
1431 ///
1432 /// assert_eq!(iter.next(), Some(-1));
1433 /// assert_eq!(iter.next(), Some(-2));
1434 /// assert_eq!(iter.next(), Some(-6));
1435 /// assert_eq!(iter.next(), None);
1436 /// ```
1437 #[inline]
1438 #[stable(feature = "rust1", since = "1.0.0")]
1439 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1440 where
1441 Self: Sized,
1442 F: FnMut(&mut St, Self::Item) -> Option<B>,
1443 {
1444 Scan::new(self, initial_state, f)
1445 }
1446
1447 /// Creates an iterator that works like map, but flattens nested structure.
1448 ///
1449 /// The [`map`] adapter is very useful, but only when the closure
1450 /// argument produces values. If it produces an iterator instead, there's
1451 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1452 /// on its own.
1453 ///
1454 /// You can think of `flat_map(f)` as the semantic equivalent
1455 /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
1456 ///
1457 /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
1458 /// one item for each element, and `flat_map()`'s closure returns an
1459 /// iterator for each element.
1460 ///
1461 /// [`map`]: Iterator::map
1462 /// [`flatten`]: Iterator::flatten
1463 ///
1464 /// # Examples
1465 ///
1466 /// ```
1467 /// let words = ["alpha", "beta", "gamma"];
1468 ///
1469 /// // chars() returns an iterator
1470 /// let merged: String = words.iter()
1471 /// .flat_map(|s| s.chars())
1472 /// .collect();
1473 /// assert_eq!(merged, "alphabetagamma");
1474 /// ```
1475 #[inline]
1476 #[stable(feature = "rust1", since = "1.0.0")]
1477 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1478 where
1479 Self: Sized,
1480 U: IntoIterator,
1481 F: FnMut(Self::Item) -> U,
1482 {
1483 FlatMap::new(self, f)
1484 }
1485
1486 /// Creates an iterator that flattens nested structure.
1487 ///
1488 /// This is useful when you have an iterator of iterators or an iterator of
1489 /// things that can be turned into iterators and you want to remove one
1490 /// level of indirection.
1491 ///
1492 /// # Examples
1493 ///
1494 /// Basic usage:
1495 ///
1496 /// ```
1497 /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
1498 /// let flattened: Vec<_> = data.into_iter().flatten().collect();
1499 /// assert_eq!(flattened, [1, 2, 3, 4, 5, 6]);
1500 /// ```
1501 ///
1502 /// Mapping and then flattening:
1503 ///
1504 /// ```
1505 /// let words = ["alpha", "beta", "gamma"];
1506 ///
1507 /// // chars() returns an iterator
1508 /// let merged: String = words.iter()
1509 /// .map(|s| s.chars())
1510 /// .flatten()
1511 /// .collect();
1512 /// assert_eq!(merged, "alphabetagamma");
1513 /// ```
1514 ///
1515 /// You can also rewrite this in terms of [`flat_map()`], which is preferable
1516 /// in this case since it conveys intent more clearly:
1517 ///
1518 /// ```
1519 /// let words = ["alpha", "beta", "gamma"];
1520 ///
1521 /// // chars() returns an iterator
1522 /// let merged: String = words.iter()
1523 /// .flat_map(|s| s.chars())
1524 /// .collect();
1525 /// assert_eq!(merged, "alphabetagamma");
1526 /// ```
1527 ///
1528 /// Flattening works on any `IntoIterator` type, including `Option` and `Result`:
1529 ///
1530 /// ```
1531 /// let options = vec![Some(123), Some(321), None, Some(231)];
1532 /// let flattened_options: Vec<_> = options.into_iter().flatten().collect();
1533 /// assert_eq!(flattened_options, [123, 321, 231]);
1534 ///
1535 /// let results = vec![Ok(123), Ok(321), Err(456), Ok(231)];
1536 /// let flattened_results: Vec<_> = results.into_iter().flatten().collect();
1537 /// assert_eq!(flattened_results, [123, 321, 231]);
1538 /// ```
1539 ///
1540 /// Flattening only removes one level of nesting at a time:
1541 ///
1542 /// ```
1543 /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
1544 ///
1545 /// let d2: Vec<_> = d3.into_iter().flatten().collect();
1546 /// assert_eq!(d2, [[1, 2], [3, 4], [5, 6], [7, 8]]);
1547 ///
1548 /// let d1: Vec<_> = d3.into_iter().flatten().flatten().collect();
1549 /// assert_eq!(d1, [1, 2, 3, 4, 5, 6, 7, 8]);
1550 /// ```
1551 ///
1552 /// Here we see that `flatten()` does not perform a "deep" flatten.
1553 /// Instead, only one level of nesting is removed. That is, if you
1554 /// `flatten()` a three-dimensional array, the result will be
1555 /// two-dimensional and not one-dimensional. To get a one-dimensional
1556 /// structure, you have to `flatten()` again.
1557 ///
1558 /// [`flat_map()`]: Iterator::flat_map
1559 #[inline]
1560 #[stable(feature = "iterator_flatten", since = "1.29.0")]
1561 fn flatten(self) -> Flatten<Self>
1562 where
1563 Self: Sized,
1564 Self::Item: IntoIterator,
1565 {
1566 Flatten::new(self)
1567 }
1568
1569 /// Calls the given function `f` for each contiguous window of size `N` over
1570 /// `self` and returns an iterator over the outputs of `f`. Like [`slice::windows()`],
1571 /// the windows during mapping overlap as well.
1572 ///
1573 /// In the following example, the closure is called three times with the
1574 /// arguments `&['a', 'b']`, `&['b', 'c']` and `&['c', 'd']` respectively.
1575 ///
1576 /// ```
1577 /// #![feature(iter_map_windows)]
1578 ///
1579 /// let strings = "abcd".chars()
1580 /// .map_windows(|[x, y]| format!("{}+{}", x, y))
1581 /// .collect::<Vec<String>>();
1582 ///
1583 /// assert_eq!(strings, vec!["a+b", "b+c", "c+d"]);
1584 /// ```
1585 ///
1586 /// Note that the const parameter `N` is usually inferred by the
1587 /// destructured argument in the closure.
1588 ///
1589 /// The returned iterator yields 𝑘 − `N` + 1 items (where 𝑘 is the number of
1590 /// items yielded by `self`). If 𝑘 is less than `N`, this method yields an
1591 /// empty iterator.
1592 ///
1593 /// The returned iterator implements [`FusedIterator`], because once `self`
1594 /// returns `None`, even if it returns a `Some(T)` again in the next iterations,
1595 /// we cannot put it into a contiguous array buffer, and thus the returned iterator
1596 /// should be fused.
1597 ///
1598 /// [`slice::windows()`]: slice::windows
1599 /// [`FusedIterator`]: crate::iter::FusedIterator
1600 ///
1601 /// # Panics
1602 ///
1603 /// Panics if `N` is zero. This check will most probably get changed to a
1604 /// compile time error before this method gets stabilized.
1605 ///
1606 /// ```should_panic
1607 /// #![feature(iter_map_windows)]
1608 ///
1609 /// let iter = std::iter::repeat(0).map_windows(|&[]| ());
1610 /// ```
1611 ///
1612 /// # Examples
1613 ///
1614 /// Building the sums of neighboring numbers.
1615 ///
1616 /// ```
1617 /// #![feature(iter_map_windows)]
1618 ///
1619 /// let mut it = [1, 3, 8, 1].iter().map_windows(|&[a, b]| a + b);
1620 /// assert_eq!(it.next(), Some(4)); // 1 + 3
1621 /// assert_eq!(it.next(), Some(11)); // 3 + 8
1622 /// assert_eq!(it.next(), Some(9)); // 8 + 1
1623 /// assert_eq!(it.next(), None);
1624 /// ```
1625 ///
1626 /// Since the elements in the following example implement `Copy`, we can
1627 /// just copy the array and get an iterator over the windows.
1628 ///
1629 /// ```
1630 /// #![feature(iter_map_windows)]
1631 ///
1632 /// let mut it = "ferris".chars().map_windows(|w: &[_; 3]| *w);
1633 /// assert_eq!(it.next(), Some(['f', 'e', 'r']));
1634 /// assert_eq!(it.next(), Some(['e', 'r', 'r']));
1635 /// assert_eq!(it.next(), Some(['r', 'r', 'i']));
1636 /// assert_eq!(it.next(), Some(['r', 'i', 's']));
1637 /// assert_eq!(it.next(), None);
1638 /// ```
1639 ///
1640 /// You can also use this function to check the sortedness of an iterator.
1641 /// For the simple case, rather use [`Iterator::is_sorted`].
1642 ///
1643 /// ```
1644 /// #![feature(iter_map_windows)]
1645 ///
1646 /// let mut it = [0.5, 1.0, 3.5, 3.0, 8.5, 8.5, f32::NAN].iter()
1647 /// .map_windows(|[a, b]| a <= b);
1648 ///
1649 /// assert_eq!(it.next(), Some(true)); // 0.5 <= 1.0
1650 /// assert_eq!(it.next(), Some(true)); // 1.0 <= 3.5
1651 /// assert_eq!(it.next(), Some(false)); // 3.5 <= 3.0
1652 /// assert_eq!(it.next(), Some(true)); // 3.0 <= 8.5
1653 /// assert_eq!(it.next(), Some(true)); // 8.5 <= 8.5
1654 /// assert_eq!(it.next(), Some(false)); // 8.5 <= NAN
1655 /// assert_eq!(it.next(), None);
1656 /// ```
1657 ///
1658 /// For non-fused iterators, they are fused after `map_windows`.
1659 ///
1660 /// ```
1661 /// #![feature(iter_map_windows)]
1662 ///
1663 /// #[derive(Default)]
1664 /// struct NonFusedIterator {
1665 /// state: i32,
1666 /// }
1667 ///
1668 /// impl Iterator for NonFusedIterator {
1669 /// type Item = i32;
1670 ///
1671 /// fn next(&mut self) -> Option<i32> {
1672 /// let val = self.state;
1673 /// self.state = self.state + 1;
1674 ///
1675 /// // yields `0..5` first, then only even numbers since `6..`.
1676 /// if val < 5 || val % 2 == 0 {
1677 /// Some(val)
1678 /// } else {
1679 /// None
1680 /// }
1681 /// }
1682 /// }
1683 ///
1684 ///
1685 /// let mut iter = NonFusedIterator::default();
1686 ///
1687 /// // yields 0..5 first.
1688 /// assert_eq!(iter.next(), Some(0));
1689 /// assert_eq!(iter.next(), Some(1));
1690 /// assert_eq!(iter.next(), Some(2));
1691 /// assert_eq!(iter.next(), Some(3));
1692 /// assert_eq!(iter.next(), Some(4));
1693 /// // then we can see our iterator going back and forth
1694 /// assert_eq!(iter.next(), None);
1695 /// assert_eq!(iter.next(), Some(6));
1696 /// assert_eq!(iter.next(), None);
1697 /// assert_eq!(iter.next(), Some(8));
1698 /// assert_eq!(iter.next(), None);
1699 ///
1700 /// // however, with `.map_windows()`, it is fused.
1701 /// let mut iter = NonFusedIterator::default()
1702 /// .map_windows(|arr: &[_; 2]| *arr);
1703 ///
1704 /// assert_eq!(iter.next(), Some([0, 1]));
1705 /// assert_eq!(iter.next(), Some([1, 2]));
1706 /// assert_eq!(iter.next(), Some([2, 3]));
1707 /// assert_eq!(iter.next(), Some([3, 4]));
1708 /// assert_eq!(iter.next(), None);
1709 ///
1710 /// // it will always return `None` after the first time.
1711 /// assert_eq!(iter.next(), None);
1712 /// assert_eq!(iter.next(), None);
1713 /// assert_eq!(iter.next(), None);
1714 /// ```
1715 #[inline]
1716 #[unstable(feature = "iter_map_windows", reason = "recently added", issue = "87155")]
1717 fn map_windows<F, R, const N: usize>(self, f: F) -> MapWindows<Self, F, N>
1718 where
1719 Self: Sized,
1720 F: FnMut(&[Self::Item; N]) -> R,
1721 {
1722 MapWindows::new(self, f)
1723 }
1724
1725 /// Creates an iterator which ends after the first [`None`].
1726 ///
1727 /// After an iterator returns [`None`], future calls may or may not yield
1728 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1729 /// [`None`] is given, it will always return [`None`] forever.
1730 ///
1731 /// Note that the [`Fuse`] wrapper is a no-op on iterators that implement
1732 /// the [`FusedIterator`] trait. `fuse()` may therefore behave incorrectly
1733 /// if the [`FusedIterator`] trait is improperly implemented.
1734 ///
1735 /// [`Some(T)`]: Some
1736 /// [`FusedIterator`]: crate::iter::FusedIterator
1737 ///
1738 /// # Examples
1739 ///
1740 /// ```
1741 /// // an iterator which alternates between Some and None
1742 /// struct Alternate {
1743 /// state: i32,
1744 /// }
1745 ///
1746 /// impl Iterator for Alternate {
1747 /// type Item = i32;
1748 ///
1749 /// fn next(&mut self) -> Option<i32> {
1750 /// let val = self.state;
1751 /// self.state = self.state + 1;
1752 ///
1753 /// // if it's even, Some(i32), else None
1754 /// (val % 2 == 0).then_some(val)
1755 /// }
1756 /// }
1757 ///
1758 /// let mut iter = Alternate { state: 0 };
1759 ///
1760 /// // we can see our iterator going back and forth
1761 /// assert_eq!(iter.next(), Some(0));
1762 /// assert_eq!(iter.next(), None);
1763 /// assert_eq!(iter.next(), Some(2));
1764 /// assert_eq!(iter.next(), None);
1765 ///
1766 /// // however, once we fuse it...
1767 /// let mut iter = iter.fuse();
1768 ///
1769 /// assert_eq!(iter.next(), Some(4));
1770 /// assert_eq!(iter.next(), None);
1771 ///
1772 /// // it will always return `None` after the first time.
1773 /// assert_eq!(iter.next(), None);
1774 /// assert_eq!(iter.next(), None);
1775 /// assert_eq!(iter.next(), None);
1776 /// ```
1777 #[inline]
1778 #[stable(feature = "rust1", since = "1.0.0")]
1779 fn fuse(self) -> Fuse<Self>
1780 where
1781 Self: Sized,
1782 {
1783 Fuse::new(self)
1784 }
1785
1786 /// Does something with each element of an iterator, passing the value on.
1787 ///
1788 /// When using iterators, you'll often chain several of them together.
1789 /// While working on such code, you might want to check out what's
1790 /// happening at various parts in the pipeline. To do that, insert
1791 /// a call to `inspect()`.
1792 ///
1793 /// It's more common for `inspect()` to be used as a debugging tool than to
1794 /// exist in your final code, but applications may find it useful in certain
1795 /// situations when errors need to be logged before being discarded.
1796 ///
1797 /// # Examples
1798 ///
1799 /// Basic usage:
1800 ///
1801 /// ```
1802 /// let a = [1, 4, 2, 3];
1803 ///
1804 /// // this iterator sequence is complex.
1805 /// let sum = a.iter()
1806 /// .cloned()
1807 /// .filter(|x| x % 2 == 0)
1808 /// .fold(0, |sum, i| sum + i);
1809 ///
1810 /// println!("{sum}");
1811 ///
1812 /// // let's add some inspect() calls to investigate what's happening
1813 /// let sum = a.iter()
1814 /// .cloned()
1815 /// .inspect(|x| println!("about to filter: {x}"))
1816 /// .filter(|x| x % 2 == 0)
1817 /// .inspect(|x| println!("made it through filter: {x}"))
1818 /// .fold(0, |sum, i| sum + i);
1819 ///
1820 /// println!("{sum}");
1821 /// ```
1822 ///
1823 /// This will print:
1824 ///
1825 /// ```text
1826 /// 6
1827 /// about to filter: 1
1828 /// about to filter: 4
1829 /// made it through filter: 4
1830 /// about to filter: 2
1831 /// made it through filter: 2
1832 /// about to filter: 3
1833 /// 6
1834 /// ```
1835 ///
1836 /// Logging errors before discarding them:
1837 ///
1838 /// ```
1839 /// let lines = ["1", "2", "a"];
1840 ///
1841 /// let sum: i32 = lines
1842 /// .iter()
1843 /// .map(|line| line.parse::<i32>())
1844 /// .inspect(|num| {
1845 /// if let Err(ref e) = *num {
1846 /// println!("Parsing error: {e}");
1847 /// }
1848 /// })
1849 /// .filter_map(Result::ok)
1850 /// .sum();
1851 ///
1852 /// println!("Sum: {sum}");
1853 /// ```
1854 ///
1855 /// This will print:
1856 ///
1857 /// ```text
1858 /// Parsing error: invalid digit found in string
1859 /// Sum: 3
1860 /// ```
1861 #[inline]
1862 #[stable(feature = "rust1", since = "1.0.0")]
1863 fn inspect<F>(self, f: F) -> Inspect<Self, F>
1864 where
1865 Self: Sized,
1866 F: FnMut(&Self::Item),
1867 {
1868 Inspect::new(self, f)
1869 }
1870
1871 /// Creates a "by reference" adapter for this instance of `Iterator`.
1872 ///
1873 /// Consuming method calls (direct or indirect calls to `next`)
1874 /// on the "by reference" adapter will consume the original iterator,
1875 /// but ownership-taking methods (those with a `self` parameter)
1876 /// only take ownership of the "by reference" iterator.
1877 ///
1878 /// This is useful for applying ownership-taking methods
1879 /// (such as `take` in the example below)
1880 /// without giving up ownership of the original iterator,
1881 /// so you can use the original iterator afterwards.
1882 ///
1883 /// Uses [`impl<I: Iterator + ?Sized> Iterator for &mut I { type Item = I::Item; ...}`](https://doc.rust-lang.org/nightly/std/iter/trait.Iterator.html#impl-Iterator-for-%26mut+I).
1884 ///
1885 /// # Examples
1886 ///
1887 /// ```
1888 /// let mut words = ["hello", "world", "of", "Rust"].into_iter();
1889 ///
1890 /// // Take the first two words.
1891 /// let hello_world: Vec<_> = words.by_ref().take(2).collect();
1892 /// assert_eq!(hello_world, vec!["hello", "world"]);
1893 ///
1894 /// // Collect the rest of the words.
1895 /// // We can only do this because we used `by_ref` earlier.
1896 /// let of_rust: Vec<_> = words.collect();
1897 /// assert_eq!(of_rust, vec!["of", "Rust"]);
1898 /// ```
1899 #[stable(feature = "rust1", since = "1.0.0")]
1900 fn by_ref(&mut self) -> &mut Self
1901 where
1902 Self: Sized,
1903 {
1904 self
1905 }
1906
1907 /// Transforms an iterator into a collection.
1908 ///
1909 /// `collect()` takes ownership of an iterator and produces whichever
1910 /// collection type you request. The iterator itself carries no knowledge of
1911 /// the eventual container; the target collection is chosen entirely by the
1912 /// type you ask `collect()` to return. This makes `collect()` one of the
1913 /// more powerful methods in the standard library, and it shows up in a wide
1914 /// variety of contexts.
1915 ///
1916 /// The most basic pattern in which `collect()` is used is to turn one
1917 /// collection into another. You take a collection, call [`iter`] on it,
1918 /// do a bunch of transformations, and then `collect()` at the end.
1919 ///
1920 /// `collect()` can also create instances of types that are not typical
1921 /// collections. For example, a [`String`] can be built from [`char`]s,
1922 /// and an iterator of [`Result<T, E>`][`Result`] items can be collected
1923 /// into `Result<Collection<T>, E>`. See the examples below for more.
1924 ///
1925 /// Because `collect()` is so general, it can cause problems with type
1926 /// inference. As such, `collect()` is one of the few times you'll see
1927 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1928 /// helps the inference algorithm understand specifically which collection
1929 /// you're trying to collect into.
1930 ///
1931 /// # Examples
1932 ///
1933 /// Basic usage:
1934 ///
1935 /// ```
1936 /// let a = [1, 2, 3];
1937 ///
1938 /// let doubled: Vec<i32> = a.iter()
1939 /// .map(|x| x * 2)
1940 /// .collect();
1941 ///
1942 /// assert_eq!(vec![2, 4, 6], doubled);
1943 /// ```
1944 ///
1945 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1946 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1947 ///
1948 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1949 ///
1950 /// ```
1951 /// use std::collections::VecDeque;
1952 ///
1953 /// let a = [1, 2, 3];
1954 ///
1955 /// let doubled: VecDeque<i32> = a.iter().map(|x| x * 2).collect();
1956 ///
1957 /// assert_eq!(2, doubled[0]);
1958 /// assert_eq!(4, doubled[1]);
1959 /// assert_eq!(6, doubled[2]);
1960 /// ```
1961 ///
1962 /// Using the 'turbofish' instead of annotating `doubled`:
1963 ///
1964 /// ```
1965 /// let a = [1, 2, 3];
1966 ///
1967 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
1968 ///
1969 /// assert_eq!(vec![2, 4, 6], doubled);
1970 /// ```
1971 ///
1972 /// Because `collect()` only cares about what you're collecting into, you can
1973 /// still use a partial type hint, `_`, with the turbofish:
1974 ///
1975 /// ```
1976 /// let a = [1, 2, 3];
1977 ///
1978 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
1979 ///
1980 /// assert_eq!(vec![2, 4, 6], doubled);
1981 /// ```
1982 ///
1983 /// Using `collect()` to make a [`String`]:
1984 ///
1985 /// ```
1986 /// let chars = ['g', 'd', 'k', 'k', 'n'];
1987 ///
1988 /// let hello: String = chars.into_iter()
1989 /// .map(|x| x as u8)
1990 /// .map(|x| (x + 1) as char)
1991 /// .collect();
1992 ///
1993 /// assert_eq!("hello", hello);
1994 /// ```
1995 ///
1996 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
1997 /// see if any of them failed:
1998 ///
1999 /// ```
2000 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
2001 ///
2002 /// let result: Result<Vec<_>, &str> = results.into_iter().collect();
2003 ///
2004 /// // gives us the first error
2005 /// assert_eq!(Err("nope"), result);
2006 ///
2007 /// let results = [Ok(1), Ok(3)];
2008 ///
2009 /// let result: Result<Vec<_>, &str> = results.into_iter().collect();
2010 ///
2011 /// // gives us the list of answers
2012 /// assert_eq!(Ok(vec![1, 3]), result);
2013 /// ```
2014 ///
2015 /// [`iter`]: Iterator::next
2016 /// [`String`]: ../../std/string/struct.String.html
2017 /// [`char`]: type@char
2018 #[inline]
2019 #[stable(feature = "rust1", since = "1.0.0")]
2020 #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
2021 #[rustc_diagnostic_item = "iterator_collect_fn"]
2022 fn collect<B: FromIterator<Self::Item>>(self) -> B
2023 where
2024 Self: Sized,
2025 {
2026 // This is too aggressive to turn on for everything all the time, but PR#137908
2027 // accidentally noticed that some rustc iterators had malformed `size_hint`s,
2028 // so this will help catch such things in debug-assertions-std runners,
2029 // even if users won't actually ever see it.
2030 if cfg!(debug_assertions) {
2031 let hint = self.size_hint();
2032 assert!(hint.1.is_none_or(|high| high >= hint.0), "Malformed size_hint {hint:?}");
2033 }
2034
2035 FromIterator::from_iter(self)
2036 }
2037
2038 /// Fallibly transforms an iterator into a collection, short circuiting if
2039 /// a failure is encountered.
2040 ///
2041 /// `try_collect()` is a variation of [`collect()`][`collect`] that allows fallible
2042 /// conversions during collection. Its main use case is simplifying conversions from
2043 /// iterators yielding [`Option<T>`][`Option`] into `Option<Collection<T>>`, or similarly for other [`Try`]
2044 /// types (e.g. [`Result`]).
2045 ///
2046 /// Importantly, `try_collect()` doesn't require that the outer [`Try`] type also implements [`FromIterator`];
2047 /// only the inner type produced on `Try::Output` must implement it. Concretely,
2048 /// this means that collecting into `ControlFlow<_, Vec<i32>>` is valid because `Vec<i32>` implements
2049 /// [`FromIterator`], even though [`ControlFlow`] doesn't.
2050 ///
2051 /// Also, if a failure is encountered during `try_collect()`, the iterator is still valid and
2052 /// may continue to be used, in which case it will continue iterating starting after the element that
2053 /// triggered the failure. See the last example below for an example of how this works.
2054 ///
2055 /// # Examples
2056 /// Successfully collecting an iterator of `Option<i32>` into `Option<Vec<i32>>`:
2057 /// ```
2058 /// #![feature(iterator_try_collect)]
2059 ///
2060 /// let u = vec![Some(1), Some(2), Some(3)];
2061 /// let v = u.into_iter().try_collect::<Vec<i32>>();
2062 /// assert_eq!(v, Some(vec![1, 2, 3]));
2063 /// ```
2064 ///
2065 /// Failing to collect in the same way:
2066 /// ```
2067 /// #![feature(iterator_try_collect)]
2068 ///
2069 /// let u = vec![Some(1), Some(2), None, Some(3)];
2070 /// let v = u.into_iter().try_collect::<Vec<i32>>();
2071 /// assert_eq!(v, None);
2072 /// ```
2073 ///
2074 /// A similar example, but with `Result`:
2075 /// ```
2076 /// #![feature(iterator_try_collect)]
2077 ///
2078 /// let u: Vec<Result<i32, ()>> = vec![Ok(1), Ok(2), Ok(3)];
2079 /// let v = u.into_iter().try_collect::<Vec<i32>>();
2080 /// assert_eq!(v, Ok(vec![1, 2, 3]));
2081 ///
2082 /// let u = vec![Ok(1), Ok(2), Err(()), Ok(3)];
2083 /// let v = u.into_iter().try_collect::<Vec<i32>>();
2084 /// assert_eq!(v, Err(()));
2085 /// ```
2086 ///
2087 /// Finally, even [`ControlFlow`] works, despite the fact that it
2088 /// doesn't implement [`FromIterator`]. Note also that the iterator can
2089 /// continue to be used, even if a failure is encountered:
2090 ///
2091 /// ```
2092 /// #![feature(iterator_try_collect)]
2093 ///
2094 /// use core::ops::ControlFlow::{Break, Continue};
2095 ///
2096 /// let u = [Continue(1), Continue(2), Break(3), Continue(4), Continue(5)];
2097 /// let mut it = u.into_iter();
2098 ///
2099 /// let v = it.try_collect::<Vec<_>>();
2100 /// assert_eq!(v, Break(3));
2101 ///
2102 /// let v = it.try_collect::<Vec<_>>();
2103 /// assert_eq!(v, Continue(vec![4, 5]));
2104 /// ```
2105 ///
2106 /// [`collect`]: Iterator::collect
2107 #[inline]
2108 #[unstable(feature = "iterator_try_collect", issue = "94047")]
2109 fn try_collect<B>(&mut self) -> ChangeOutputType<Self::Item, B>
2110 where
2111 Self: Sized,
2112 Self::Item: Try<Residual: Residual<B>>,
2113 B: FromIterator<<Self::Item as Try>::Output>,
2114 {
2115 try_process(ByRefSized(self), |i| i.collect())
2116 }
2117
2118 /// Collects all the items from an iterator into a collection.
2119 ///
2120 /// This method consumes the iterator and adds all its items to the
2121 /// passed collection. The collection is then returned, so the call chain
2122 /// can be continued.
2123 ///
2124 /// This is useful when you already have a collection and want to add
2125 /// the iterator items to it.
2126 ///
2127 /// This method is a convenience method to call [Extend::extend](trait.Extend.html),
2128 /// but instead of being called on a collection, it's called on an iterator.
2129 ///
2130 /// # Examples
2131 ///
2132 /// Basic usage:
2133 ///
2134 /// ```
2135 /// #![feature(iter_collect_into)]
2136 ///
2137 /// let a = [1, 2, 3];
2138 /// let mut vec: Vec::<i32> = vec![0, 1];
2139 ///
2140 /// a.iter().map(|x| x * 2).collect_into(&mut vec);
2141 /// a.iter().map(|x| x * 10).collect_into(&mut vec);
2142 ///
2143 /// assert_eq!(vec, vec![0, 1, 2, 4, 6, 10, 20, 30]);
2144 /// ```
2145 ///
2146 /// `Vec` can have a manual set capacity to avoid reallocating it:
2147 ///
2148 /// ```
2149 /// #![feature(iter_collect_into)]
2150 ///
2151 /// let a = [1, 2, 3];
2152 /// let mut vec: Vec::<i32> = Vec::with_capacity(6);
2153 ///
2154 /// a.iter().map(|x| x * 2).collect_into(&mut vec);
2155 /// a.iter().map(|x| x * 10).collect_into(&mut vec);
2156 ///
2157 /// assert_eq!(6, vec.capacity());
2158 /// assert_eq!(vec, vec![2, 4, 6, 10, 20, 30]);
2159 /// ```
2160 ///
2161 /// The returned mutable reference can be used to continue the call chain:
2162 ///
2163 /// ```
2164 /// #![feature(iter_collect_into)]
2165 ///
2166 /// let a = [1, 2, 3];
2167 /// let mut vec: Vec::<i32> = Vec::with_capacity(6);
2168 ///
2169 /// let count = a.iter().collect_into(&mut vec).iter().count();
2170 ///
2171 /// assert_eq!(count, vec.len());
2172 /// assert_eq!(vec, vec![1, 2, 3]);
2173 ///
2174 /// let count = a.iter().collect_into(&mut vec).iter().count();
2175 ///
2176 /// assert_eq!(count, vec.len());
2177 /// assert_eq!(vec, vec![1, 2, 3, 1, 2, 3]);
2178 /// ```
2179 #[inline]
2180 #[unstable(feature = "iter_collect_into", reason = "new API", issue = "94780")]
2181 fn collect_into<E: Extend<Self::Item>>(self, collection: &mut E) -> &mut E
2182 where
2183 Self: Sized,
2184 {
2185 collection.extend(self);
2186 collection
2187 }
2188
2189 /// Consumes an iterator, creating two collections from it.
2190 ///
2191 /// The predicate passed to `partition()` can return `true`, or `false`.
2192 /// `partition()` returns a pair, all of the elements for which it returned
2193 /// `true`, and all of the elements for which it returned `false`.
2194 ///
2195 /// See also [`is_partitioned()`] and [`partition_in_place()`].
2196 ///
2197 /// [`is_partitioned()`]: Iterator::is_partitioned
2198 /// [`partition_in_place()`]: Iterator::partition_in_place
2199 ///
2200 /// # Examples
2201 ///
2202 /// ```
2203 /// let a = [1, 2, 3];
2204 ///
2205 /// let (even, odd): (Vec<_>, Vec<_>) = a
2206 /// .into_iter()
2207 /// .partition(|n| n % 2 == 0);
2208 ///
2209 /// assert_eq!(even, [2]);
2210 /// assert_eq!(odd, [1, 3]);
2211 /// ```
2212 #[stable(feature = "rust1", since = "1.0.0")]
2213 fn partition<B, F>(self, f: F) -> (B, B)
2214 where
2215 Self: Sized,
2216 B: Default + Extend<Self::Item>,
2217 F: FnMut(&Self::Item) -> bool,
2218 {
2219 #[inline]
2220 fn extend<'a, T, B: Extend<T>>(
2221 mut f: impl FnMut(&T) -> bool + 'a,
2222 left: &'a mut B,
2223 right: &'a mut B,
2224 ) -> impl FnMut((), T) + 'a {
2225 move |(), x| {
2226 if f(&x) {
2227 left.extend_one(x);
2228 } else {
2229 right.extend_one(x);
2230 }
2231 }
2232 }
2233
2234 let mut left: B = Default::default();
2235 let mut right: B = Default::default();
2236
2237 self.fold((), extend(f, &mut left, &mut right));
2238
2239 (left, right)
2240 }
2241
2242 /// Reorders the elements of this iterator *in-place* according to the given predicate,
2243 /// such that all those that return `true` precede all those that return `false`.
2244 /// Returns the number of `true` elements found.
2245 ///
2246 /// The relative order of partitioned items is not maintained.
2247 ///
2248 /// # Current implementation
2249 ///
2250 /// The current algorithm tries to find the first element for which the predicate evaluates
2251 /// to false and the last element for which it evaluates to true, and repeatedly swaps them.
2252 ///
2253 /// Time complexity: *O*(*n*)
2254 ///
2255 /// See also [`is_partitioned()`] and [`partition()`].
2256 ///
2257 /// [`is_partitioned()`]: Iterator::is_partitioned
2258 /// [`partition()`]: Iterator::partition
2259 ///
2260 /// # Examples
2261 ///
2262 /// ```
2263 /// #![feature(iter_partition_in_place)]
2264 ///
2265 /// let mut a = [1, 2, 3, 4, 5, 6, 7];
2266 ///
2267 /// // Partition in-place between evens and odds
2268 /// let i = a.iter_mut().partition_in_place(|n| n % 2 == 0);
2269 ///
2270 /// assert_eq!(i, 3);
2271 /// assert!(a[..i].iter().all(|n| n % 2 == 0)); // evens
2272 /// assert!(a[i..].iter().all(|n| n % 2 == 1)); // odds
2273 /// ```
2274 #[unstable(feature = "iter_partition_in_place", reason = "new API", issue = "62543")]
2275 fn partition_in_place<'a, T: 'a, P>(mut self, ref mut predicate: P) -> usize
2276 where
2277 Self: Sized + DoubleEndedIterator<Item = &'a mut T>,
2278 P: FnMut(&T) -> bool,
2279 {
2280 // FIXME: should we worry about the count overflowing? The only way to have more than
2281 // `usize::MAX` mutable references is with ZSTs, which aren't useful to partition...
2282
2283 // These closure "factory" functions exist to avoid genericity in `Self`.
2284
2285 #[inline]
2286 fn is_false<'a, T>(
2287 predicate: &'a mut impl FnMut(&T) -> bool,
2288 true_count: &'a mut usize,
2289 ) -> impl FnMut(&&mut T) -> bool + 'a {
2290 move |x| {
2291 let p = predicate(&**x);
2292 *true_count += p as usize;
2293 !p
2294 }
2295 }
2296
2297 #[inline]
2298 fn is_true<T>(predicate: &mut impl FnMut(&T) -> bool) -> impl FnMut(&&mut T) -> bool + '_ {
2299 move |x| predicate(&**x)
2300 }
2301
2302 // Repeatedly find the first `false` and swap it with the last `true`.
2303 let mut true_count = 0;
2304 while let Some(head) = self.find(is_false(predicate, &mut true_count)) {
2305 if let Some(tail) = self.rfind(is_true(predicate)) {
2306 crate::mem::swap(head, tail);
2307 true_count += 1;
2308 } else {
2309 break;
2310 }
2311 }
2312 true_count
2313 }
2314
2315 /// Checks if the elements of this iterator are partitioned according to the given predicate,
2316 /// such that all those that return `true` precede all those that return `false`.
2317 ///
2318 /// See also [`partition()`] and [`partition_in_place()`].
2319 ///
2320 /// [`partition()`]: Iterator::partition
2321 /// [`partition_in_place()`]: Iterator::partition_in_place
2322 ///
2323 /// # Examples
2324 ///
2325 /// ```
2326 /// #![feature(iter_is_partitioned)]
2327 ///
2328 /// assert!("Iterator".chars().is_partitioned(char::is_uppercase));
2329 /// assert!(!"IntoIterator".chars().is_partitioned(char::is_uppercase));
2330 /// ```
2331 #[unstable(feature = "iter_is_partitioned", reason = "new API", issue = "62544")]
2332 fn is_partitioned<P>(mut self, mut predicate: P) -> bool
2333 where
2334 Self: Sized,
2335 P: FnMut(Self::Item) -> bool,
2336 {
2337 // Either all items test `true`, or the first clause stops at `false`
2338 // and we check that there are no more `true` items after that.
2339 self.all(&mut predicate) || !self.any(predicate)
2340 }
2341
2342 /// An iterator method that applies a function as long as it returns
2343 /// successfully, producing a single, final value.
2344 ///
2345 /// `try_fold()` takes two arguments: an initial value, and a closure with
2346 /// two arguments: an 'accumulator', and an element. The closure either
2347 /// returns successfully, with the value that the accumulator should have
2348 /// for the next iteration, or it returns failure, with an error value that
2349 /// is propagated back to the caller immediately (short-circuiting).
2350 ///
2351 /// The initial value is the value the accumulator will have on the first
2352 /// call. If applying the closure succeeded against every element of the
2353 /// iterator, `try_fold()` returns the final accumulator as success.
2354 ///
2355 /// Folding is useful whenever you have a collection of something, and want
2356 /// to produce a single value from it.
2357 ///
2358 /// # Note to Implementors
2359 ///
2360 /// Several of the other (forward) methods have default implementations in
2361 /// terms of this one, so try to implement this explicitly if it can
2362 /// do something better than the default `for` loop implementation.
2363 ///
2364 /// In particular, try to have this call `try_fold()` on the internal parts
2365 /// from which this iterator is composed. If multiple calls are needed,
2366 /// the `?` operator may be convenient for chaining the accumulator value
2367 /// along, but beware any invariants that need to be upheld before those
2368 /// early returns. This is a `&mut self` method, so iteration needs to be
2369 /// resumable after hitting an error here.
2370 ///
2371 /// # Examples
2372 ///
2373 /// Basic usage:
2374 ///
2375 /// ```
2376 /// let a = [1, 2, 3];
2377 ///
2378 /// // the checked sum of all of the elements of the array
2379 /// let sum = a.into_iter().try_fold(0i8, |acc, x| acc.checked_add(x));
2380 ///
2381 /// assert_eq!(sum, Some(6));
2382 /// ```
2383 ///
2384 /// Short-circuiting:
2385 ///
2386 /// ```
2387 /// let a = [10, 20, 30, 100, 40, 50];
2388 /// let mut iter = a.into_iter();
2389 ///
2390 /// // This sum overflows when adding the 100 element
2391 /// let sum = iter.try_fold(0i8, |acc, x| acc.checked_add(x));
2392 /// assert_eq!(sum, None);
2393 ///
2394 /// // Because it short-circuited, the remaining elements are still
2395 /// // available through the iterator.
2396 /// assert_eq!(iter.len(), 2);
2397 /// assert_eq!(iter.next(), Some(40));
2398 /// ```
2399 ///
2400 /// While you cannot `break` from a closure, the [`ControlFlow`] type allows
2401 /// a similar idea:
2402 ///
2403 /// ```
2404 /// use std::ops::ControlFlow;
2405 ///
2406 /// let triangular = (1..30).try_fold(0_i8, |prev, x| {
2407 /// if let Some(next) = prev.checked_add(x) {
2408 /// ControlFlow::Continue(next)
2409 /// } else {
2410 /// ControlFlow::Break(prev)
2411 /// }
2412 /// });
2413 /// assert_eq!(triangular, ControlFlow::Break(120));
2414 ///
2415 /// let triangular = (1..30).try_fold(0_u64, |prev, x| {
2416 /// if let Some(next) = prev.checked_add(x) {
2417 /// ControlFlow::Continue(next)
2418 /// } else {
2419 /// ControlFlow::Break(prev)
2420 /// }
2421 /// });
2422 /// assert_eq!(triangular, ControlFlow::Continue(435));
2423 /// ```
2424 #[inline]
2425 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
2426 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
2427 where
2428 Self: Sized,
2429 F: FnMut(B, Self::Item) -> R,
2430 R: Try<Output = B>,
2431 {
2432 let mut accum = init;
2433 while let Some(x) = self.next() {
2434 accum = f(accum, x)?;
2435 }
2436 try { accum }
2437 }
2438
2439 /// An iterator method that applies a fallible function to each item in the
2440 /// iterator, stopping at the first error and returning that error.
2441 ///
2442 /// This can also be thought of as the fallible form of [`for_each()`]
2443 /// or as the stateless version of [`try_fold()`].
2444 ///
2445 /// [`for_each()`]: Iterator::for_each
2446 /// [`try_fold()`]: Iterator::try_fold
2447 ///
2448 /// # Examples
2449 ///
2450 /// ```
2451 /// use std::fs::rename;
2452 /// use std::io::{stdout, Write};
2453 /// use std::path::Path;
2454 ///
2455 /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
2456 ///
2457 /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{x}"));
2458 /// assert!(res.is_ok());
2459 ///
2460 /// let mut it = data.iter().cloned();
2461 /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
2462 /// assert!(res.is_err());
2463 /// // It short-circuited, so the remaining items are still in the iterator:
2464 /// assert_eq!(it.next(), Some("stale_bread.json"));
2465 /// ```
2466 ///
2467 /// The [`ControlFlow`] type can be used with this method for the situations
2468 /// in which you'd use `break` and `continue` in a normal loop:
2469 ///
2470 /// ```
2471 /// use std::ops::ControlFlow;
2472 ///
2473 /// let r = (2..100).try_for_each(|x| {
2474 /// if 323 % x == 0 {
2475 /// return ControlFlow::Break(x)
2476 /// }
2477 ///
2478 /// ControlFlow::Continue(())
2479 /// });
2480 /// assert_eq!(r, ControlFlow::Break(17));
2481 /// ```
2482 #[inline]
2483 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
2484 fn try_for_each<F, R>(&mut self, f: F) -> R
2485 where
2486 Self: Sized,
2487 F: FnMut(Self::Item) -> R,
2488 R: Try<Output = ()>,
2489 {
2490 #[inline]
2491 fn call<T, R>(mut f: impl FnMut(T) -> R) -> impl FnMut((), T) -> R {
2492 move |(), x| f(x)
2493 }
2494
2495 self.try_fold((), call(f))
2496 }
2497
2498 /// Folds every element into an accumulator by applying an operation,
2499 /// returning the final result.
2500 ///
2501 /// `fold()` takes two arguments: an initial value, and a closure with two
2502 /// arguments: an 'accumulator', and an element. The closure returns the value that
2503 /// the accumulator should have for the next iteration.
2504 ///
2505 /// The initial value is the value the accumulator will have on the first
2506 /// call.
2507 ///
2508 /// After applying this closure to every element of the iterator, `fold()`
2509 /// returns the accumulator.
2510 ///
2511 /// This operation is sometimes called 'reduce' or 'inject'.
2512 ///
2513 /// Folding is useful whenever you have a collection of something, and want
2514 /// to produce a single value from it.
2515 ///
2516 /// Note: `fold()`, and similar methods that traverse the entire iterator,
2517 /// might not terminate for infinite iterators, even on traits for which a
2518 /// result is determinable in finite time.
2519 ///
2520 /// Note: [`reduce()`] can be used to use the first element as the initial
2521 /// value, if the accumulator type and item type is the same.
2522 ///
2523 /// Note: `fold()` combines elements in a *left-associative* fashion. For associative
2524 /// operators like `+`, the order the elements are combined in is not important, but for non-associative
2525 /// operators like `-` the order will affect the final result.
2526 /// For a *right-associative* version of `fold()`, see [`DoubleEndedIterator::rfold()`].
2527 ///
2528 /// # Note to Implementors
2529 ///
2530 /// Several of the other (forward) methods have default implementations in
2531 /// terms of this one, so try to implement this explicitly if it can
2532 /// do something better than the default `for` loop implementation.
2533 ///
2534 /// In particular, try to have this call `fold()` on the internal parts
2535 /// from which this iterator is composed.
2536 ///
2537 /// # Examples
2538 ///
2539 /// Basic usage:
2540 ///
2541 /// ```
2542 /// let a = [1, 2, 3];
2543 ///
2544 /// // the sum of all of the elements of the array
2545 /// let sum = a.iter().fold(0, |acc, x| acc + x);
2546 ///
2547 /// assert_eq!(sum, 6);
2548 /// ```
2549 ///
2550 /// Let's walk through each step of the iteration here:
2551 ///
2552 /// | element | acc | x | result |
2553 /// |---------|-----|---|--------|
2554 /// | | 0 | | |
2555 /// | 1 | 0 | 1 | 1 |
2556 /// | 2 | 1 | 2 | 3 |
2557 /// | 3 | 3 | 3 | 6 |
2558 ///
2559 /// And so, our final result, `6`.
2560 ///
2561 /// This example demonstrates the left-associative nature of `fold()`:
2562 /// it builds a string, starting with an initial value
2563 /// and continuing with each element from the front until the back:
2564 ///
2565 /// ```
2566 /// let numbers = [1, 2, 3, 4, 5];
2567 ///
2568 /// let zero = "0".to_string();
2569 ///
2570 /// let result = numbers.iter().fold(zero, |acc, &x| {
2571 /// format!("({acc} + {x})")
2572 /// });
2573 ///
2574 /// assert_eq!(result, "(((((0 + 1) + 2) + 3) + 4) + 5)");
2575 /// ```
2576 /// It's common for people who haven't used iterators a lot to
2577 /// use a `for` loop with a list of things to build up a result. Those
2578 /// can be turned into `fold()`s:
2579 ///
2580 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
2581 ///
2582 /// ```
2583 /// let numbers = [1, 2, 3, 4, 5];
2584 ///
2585 /// let mut result = 0;
2586 ///
2587 /// // for loop:
2588 /// for i in &numbers {
2589 /// result = result + i;
2590 /// }
2591 ///
2592 /// // fold:
2593 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
2594 ///
2595 /// // they're the same
2596 /// assert_eq!(result, result2);
2597 /// ```
2598 ///
2599 /// [`reduce()`]: Iterator::reduce
2600 #[doc(alias = "inject", alias = "foldl")]
2601 #[inline]
2602 #[stable(feature = "rust1", since = "1.0.0")]
2603 fn fold<B, F>(mut self, init: B, mut f: F) -> B
2604 where
2605 Self: Sized,
2606 F: FnMut(B, Self::Item) -> B,
2607 {
2608 let mut accum = init;
2609 while let Some(x) = self.next() {
2610 accum = f(accum, x);
2611 }
2612 accum
2613 }
2614
2615 /// Reduces the elements to a single one, by repeatedly applying a reducing
2616 /// operation.
2617 ///
2618 /// If the iterator is empty, returns [`None`]; otherwise, returns the
2619 /// result of the reduction.
2620 ///
2621 /// The reducing function is a closure with two arguments: an 'accumulator', and an element.
2622 /// For iterators with at least one element, this is the same as [`fold()`]
2623 /// with the first element of the iterator as the initial accumulator value, folding
2624 /// every subsequent element into it.
2625 ///
2626 /// [`fold()`]: Iterator::fold
2627 ///
2628 /// # Example
2629 ///
2630 /// ```
2631 /// let reduced: i32 = (1..10).reduce(|acc, e| acc + e).unwrap_or(0);
2632 /// assert_eq!(reduced, 45);
2633 ///
2634 /// // Which is equivalent to doing it with `fold`:
2635 /// let folded: i32 = (1..10).fold(0, |acc, e| acc + e);
2636 /// assert_eq!(reduced, folded);
2637 /// ```
2638 #[inline]
2639 #[stable(feature = "iterator_fold_self", since = "1.51.0")]
2640 fn reduce<F>(mut self, f: F) -> Option<Self::Item>
2641 where
2642 Self: Sized,
2643 F: FnMut(Self::Item, Self::Item) -> Self::Item,
2644 {
2645 let first = self.next()?;
2646 Some(self.fold(first, f))
2647 }
2648
2649 /// Reduces the elements to a single one by repeatedly applying a reducing operation. If the
2650 /// closure returns a failure, the failure is propagated back to the caller immediately.
2651 ///
2652 /// The return type of this method depends on the return type of the closure. If the closure
2653 /// returns `Result<Self::Item, E>`, then this function will return `Result<Option<Self::Item>,
2654 /// E>`. If the closure returns `Option<Self::Item>`, then this function will return
2655 /// `Option<Option<Self::Item>>`.
2656 ///
2657 /// When called on an empty iterator, this function will return either `Some(None)` or
2658 /// `Ok(None)` depending on the type of the provided closure.
2659 ///
2660 /// For iterators with at least one element, this is essentially the same as calling
2661 /// [`try_fold()`] with the first element of the iterator as the initial accumulator value.
2662 ///
2663 /// [`try_fold()`]: Iterator::try_fold
2664 ///
2665 /// # Examples
2666 ///
2667 /// Safely calculate the sum of a series of numbers:
2668 ///
2669 /// ```
2670 /// #![feature(iterator_try_reduce)]
2671 ///
2672 /// let numbers: Vec<usize> = vec![10, 20, 5, 23, 0];
2673 /// let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));
2674 /// assert_eq!(sum, Some(Some(58)));
2675 /// ```
2676 ///
2677 /// Determine when a reduction short circuited:
2678 ///
2679 /// ```
2680 /// #![feature(iterator_try_reduce)]
2681 ///
2682 /// let numbers = vec![1, 2, 3, usize::MAX, 4, 5];
2683 /// let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));
2684 /// assert_eq!(sum, None);
2685 /// ```
2686 ///
2687 /// Determine when a reduction was not performed because there are no elements:
2688 ///
2689 /// ```
2690 /// #![feature(iterator_try_reduce)]
2691 ///
2692 /// let numbers: Vec<usize> = Vec::new();
2693 /// let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));
2694 /// assert_eq!(sum, Some(None));
2695 /// ```
2696 ///
2697 /// Use a [`Result`] instead of an [`Option`]:
2698 ///
2699 /// ```
2700 /// #![feature(iterator_try_reduce)]
2701 ///
2702 /// let numbers = vec!["1", "2", "3", "4", "5"];
2703 /// let max: Result<Option<_>, <usize as std::str::FromStr>::Err> =
2704 /// numbers.into_iter().try_reduce(|x, y| {
2705 /// if x.parse::<usize>()? > y.parse::<usize>()? { Ok(x) } else { Ok(y) }
2706 /// });
2707 /// assert_eq!(max, Ok(Some("5")));
2708 /// ```
2709 #[inline]
2710 #[unstable(feature = "iterator_try_reduce", reason = "new API", issue = "87053")]
2711 fn try_reduce<R>(
2712 &mut self,
2713 f: impl FnMut(Self::Item, Self::Item) -> R,
2714 ) -> ChangeOutputType<R, Option<R::Output>>
2715 where
2716 Self: Sized,
2717 R: Try<Output = Self::Item, Residual: Residual<Option<Self::Item>>>,
2718 {
2719 let first = match self.next() {
2720 Some(i) => i,
2721 None => return Try::from_output(None),
2722 };
2723
2724 match self.try_fold(first, f).branch() {
2725 ControlFlow::Break(r) => FromResidual::from_residual(r),
2726 ControlFlow::Continue(i) => Try::from_output(Some(i)),
2727 }
2728 }
2729
2730 /// Tests if every element of the iterator matches a predicate.
2731 ///
2732 /// `all()` takes a closure that returns `true` or `false`. It applies
2733 /// this closure to each element of the iterator, and if they all return
2734 /// `true`, then so does `all()`. If any of them return `false`, it
2735 /// returns `false`.
2736 ///
2737 /// `all()` is short-circuiting; in other words, it will stop processing
2738 /// as soon as it finds a `false`, given that no matter what else happens,
2739 /// the result will also be `false`.
2740 ///
2741 /// An empty iterator returns `true`.
2742 ///
2743 /// # Examples
2744 ///
2745 /// Basic usage:
2746 ///
2747 /// ```
2748 /// let a = [1, 2, 3];
2749 ///
2750 /// assert!(a.into_iter().all(|x| x > 0));
2751 ///
2752 /// assert!(!a.into_iter().all(|x| x > 2));
2753 /// ```
2754 ///
2755 /// Stopping at the first `false`:
2756 ///
2757 /// ```
2758 /// let a = [1, 2, 3];
2759 ///
2760 /// let mut iter = a.into_iter();
2761 ///
2762 /// assert!(!iter.all(|x| x != 2));
2763 ///
2764 /// // we can still use `iter`, as there are more elements.
2765 /// assert_eq!(iter.next(), Some(3));
2766 /// ```
2767 #[inline]
2768 #[stable(feature = "rust1", since = "1.0.0")]
2769 fn all<F>(&mut self, f: F) -> bool
2770 where
2771 Self: Sized,
2772 F: FnMut(Self::Item) -> bool,
2773 {
2774 #[inline]
2775 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> {
2776 move |(), x| {
2777 if f(x) { ControlFlow::Continue(()) } else { ControlFlow::Break(()) }
2778 }
2779 }
2780 self.try_fold((), check(f)) == ControlFlow::Continue(())
2781 }
2782
2783 /// Tests if any element of the iterator matches a predicate.
2784 ///
2785 /// `any()` takes a closure that returns `true` or `false`. It applies
2786 /// this closure to each element of the iterator, and if any of them return
2787 /// `true`, then so does `any()`. If they all return `false`, it
2788 /// returns `false`.
2789 ///
2790 /// `any()` is short-circuiting; in other words, it will stop processing
2791 /// as soon as it finds a `true`, given that no matter what else happens,
2792 /// the result will also be `true`.
2793 ///
2794 /// An empty iterator returns `false`.
2795 ///
2796 /// # Examples
2797 ///
2798 /// Basic usage:
2799 ///
2800 /// ```
2801 /// let a = [1, 2, 3];
2802 ///
2803 /// assert!(a.into_iter().any(|x| x > 0));
2804 ///
2805 /// assert!(!a.into_iter().any(|x| x > 5));
2806 /// ```
2807 ///
2808 /// Stopping at the first `true`:
2809 ///
2810 /// ```
2811 /// let a = [1, 2, 3];
2812 ///
2813 /// let mut iter = a.into_iter();
2814 ///
2815 /// assert!(iter.any(|x| x != 2));
2816 ///
2817 /// // we can still use `iter`, as there are more elements.
2818 /// assert_eq!(iter.next(), Some(2));
2819 /// ```
2820 #[inline]
2821 #[stable(feature = "rust1", since = "1.0.0")]
2822 fn any<F>(&mut self, f: F) -> bool
2823 where
2824 Self: Sized,
2825 F: FnMut(Self::Item) -> bool,
2826 {
2827 #[inline]
2828 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> {
2829 move |(), x| {
2830 if f(x) { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
2831 }
2832 }
2833
2834 self.try_fold((), check(f)) == ControlFlow::Break(())
2835 }
2836
2837 /// Searches for an element of an iterator that satisfies a predicate.
2838 ///
2839 /// `find()` takes a closure that returns `true` or `false`. It applies
2840 /// this closure to each element of the iterator, and if any of them return
2841 /// `true`, then `find()` returns [`Some(element)`]. If they all return
2842 /// `false`, it returns [`None`].
2843 ///
2844 /// `find()` is short-circuiting; in other words, it will stop processing
2845 /// as soon as the closure returns `true`.
2846 ///
2847 /// Because `find()` takes a reference, and many iterators iterate over
2848 /// references, this leads to a possibly confusing situation where the
2849 /// argument is a double reference. You can see this effect in the
2850 /// examples below, with `&&x`.
2851 ///
2852 /// If you need the index of the element, see [`position()`].
2853 ///
2854 /// [`Some(element)`]: Some
2855 /// [`position()`]: Iterator::position
2856 ///
2857 /// # Examples
2858 ///
2859 /// Basic usage:
2860 ///
2861 /// ```
2862 /// let a = [1, 2, 3];
2863 ///
2864 /// assert_eq!(a.into_iter().find(|&x| x == 2), Some(2));
2865 /// assert_eq!(a.into_iter().find(|&x| x == 5), None);
2866 /// ```
2867 ///
2868 /// Iterating over references:
2869 ///
2870 /// ```
2871 /// let a = [1, 2, 3];
2872 ///
2873 /// // `iter()` yields references i.e. `&i32` and `find()` takes a
2874 /// // reference to each element.
2875 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
2876 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
2877 /// ```
2878 ///
2879 /// Stopping at the first `true`:
2880 ///
2881 /// ```
2882 /// let a = [1, 2, 3];
2883 ///
2884 /// let mut iter = a.into_iter();
2885 ///
2886 /// assert_eq!(iter.find(|&x| x == 2), Some(2));
2887 ///
2888 /// // we can still use `iter`, as there are more elements.
2889 /// assert_eq!(iter.next(), Some(3));
2890 /// ```
2891 ///
2892 /// Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`.
2893 #[inline]
2894 #[stable(feature = "rust1", since = "1.0.0")]
2895 fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
2896 where
2897 Self: Sized,
2898 P: FnMut(&Self::Item) -> bool,
2899 {
2900 #[inline]
2901 fn check<T>(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut((), T) -> ControlFlow<T> {
2902 move |(), x| {
2903 if predicate(&x) { ControlFlow::Break(x) } else { ControlFlow::Continue(()) }
2904 }
2905 }
2906
2907 self.try_fold((), check(predicate)).break_value()
2908 }
2909
2910 /// Applies function to the elements of iterator and returns
2911 /// the first non-none result.
2912 ///
2913 /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
2914 ///
2915 /// # Examples
2916 ///
2917 /// ```
2918 /// let a = ["lol", "NaN", "2", "5"];
2919 ///
2920 /// let first_number = a.iter().find_map(|s| s.parse().ok());
2921 ///
2922 /// assert_eq!(first_number, Some(2));
2923 /// ```
2924 #[inline]
2925 #[stable(feature = "iterator_find_map", since = "1.30.0")]
2926 fn find_map<B, F>(&mut self, f: F) -> Option<B>
2927 where
2928 Self: Sized,
2929 F: FnMut(Self::Item) -> Option<B>,
2930 {
2931 #[inline]
2932 fn check<T, B>(mut f: impl FnMut(T) -> Option<B>) -> impl FnMut((), T) -> ControlFlow<B> {
2933 move |(), x| match f(x) {
2934 Some(x) => ControlFlow::Break(x),
2935 None => ControlFlow::Continue(()),
2936 }
2937 }
2938
2939 self.try_fold((), check(f)).break_value()
2940 }
2941
2942 /// Applies function to the elements of iterator and returns
2943 /// the first true result or the first error.
2944 ///
2945 /// The return type of this method depends on the return type of the closure.
2946 /// If you return `Result<bool, E>` from the closure, you'll get a `Result<Option<Self::Item>, E>`.
2947 /// If you return `Option<bool>` from the closure, you'll get an `Option<Option<Self::Item>>`.
2948 ///
2949 /// # Examples
2950 ///
2951 /// ```
2952 /// #![feature(try_find)]
2953 ///
2954 /// let a = ["1", "2", "lol", "NaN", "5"];
2955 ///
2956 /// let is_my_num = |s: &str, search: i32| -> Result<bool, std::num::ParseIntError> {
2957 /// Ok(s.parse::<i32>()? == search)
2958 /// };
2959 ///
2960 /// let result = a.into_iter().try_find(|&s| is_my_num(s, 2));
2961 /// assert_eq!(result, Ok(Some("2")));
2962 ///
2963 /// let result = a.into_iter().try_find(|&s| is_my_num(s, 5));
2964 /// assert!(result.is_err());
2965 /// ```
2966 ///
2967 /// This also supports other types which implement [`Try`], not just [`Result`].
2968 ///
2969 /// ```
2970 /// #![feature(try_find)]
2971 ///
2972 /// use std::num::NonZero;
2973 ///
2974 /// let a = [3, 5, 7, 4, 9, 0, 11u32];
2975 /// let result = a.into_iter().try_find(|&x| NonZero::new(x).map(|y| y.is_power_of_two()));
2976 /// assert_eq!(result, Some(Some(4)));
2977 /// let result = a.into_iter().take(3).try_find(|&x| NonZero::new(x).map(|y| y.is_power_of_two()));
2978 /// assert_eq!(result, Some(None));
2979 /// let result = a.into_iter().rev().try_find(|&x| NonZero::new(x).map(|y| y.is_power_of_two()));
2980 /// assert_eq!(result, None);
2981 /// ```
2982 #[inline]
2983 #[unstable(feature = "try_find", reason = "new API", issue = "63178")]
2984 fn try_find<R>(
2985 &mut self,
2986 f: impl FnMut(&Self::Item) -> R,
2987 ) -> ChangeOutputType<R, Option<Self::Item>>
2988 where
2989 Self: Sized,
2990 R: Try<Output = bool, Residual: Residual<Option<Self::Item>>>,
2991 {
2992 #[inline]
2993 fn check<I, V, R>(
2994 mut f: impl FnMut(&I) -> V,
2995 ) -> impl FnMut((), I) -> ControlFlow<R::TryType>
2996 where
2997 V: Try<Output = bool, Residual = R>,
2998 R: Residual<Option<I>>,
2999 {
3000 move |(), x| match f(&x).branch() {
3001 ControlFlow::Continue(false) => ControlFlow::Continue(()),
3002 ControlFlow::Continue(true) => ControlFlow::Break(Try::from_output(Some(x))),
3003 ControlFlow::Break(r) => ControlFlow::Break(FromResidual::from_residual(r)),
3004 }
3005 }
3006
3007 match self.try_fold((), check(f)) {
3008 ControlFlow::Break(x) => x,
3009 ControlFlow::Continue(()) => Try::from_output(None),
3010 }
3011 }
3012
3013 /// Searches for an element in an iterator, returning its index.
3014 ///
3015 /// `position()` takes a closure that returns `true` or `false`. It applies
3016 /// this closure to each element of the iterator, and if one of them
3017 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
3018 /// them return `false`, it returns [`None`].
3019 ///
3020 /// `position()` is short-circuiting; in other words, it will stop
3021 /// processing as soon as it finds a `true`.
3022 ///
3023 /// # Overflow Behavior
3024 ///
3025 /// The method does no guarding against overflows, so if there are more
3026 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
3027 /// result or panics. If overflow checks are enabled, a panic is
3028 /// guaranteed.
3029 ///
3030 /// # Panics
3031 ///
3032 /// This function might panic if the iterator has more than `usize::MAX`
3033 /// non-matching elements.
3034 ///
3035 /// [`Some(index)`]: Some
3036 ///
3037 /// # Examples
3038 ///
3039 /// Basic usage:
3040 ///
3041 /// ```
3042 /// let a = [1, 2, 3];
3043 ///
3044 /// assert_eq!(a.into_iter().position(|x| x == 2), Some(1));
3045 ///
3046 /// assert_eq!(a.into_iter().position(|x| x == 5), None);
3047 /// ```
3048 ///
3049 /// Stopping at the first `true`:
3050 ///
3051 /// ```
3052 /// let a = [1, 2, 3, 4];
3053 ///
3054 /// let mut iter = a.into_iter();
3055 ///
3056 /// assert_eq!(iter.position(|x| x >= 2), Some(1));
3057 ///
3058 /// // we can still use `iter`, as there are more elements.
3059 /// assert_eq!(iter.next(), Some(3));
3060 ///
3061 /// // The returned index depends on iterator state
3062 /// assert_eq!(iter.position(|x| x == 4), Some(0));
3063 ///
3064 /// ```
3065 #[inline]
3066 #[stable(feature = "rust1", since = "1.0.0")]
3067 fn position<P>(&mut self, predicate: P) -> Option<usize>
3068 where
3069 Self: Sized,
3070 P: FnMut(Self::Item) -> bool,
3071 {
3072 #[inline]
3073 fn check<'a, T>(
3074 mut predicate: impl FnMut(T) -> bool + 'a,
3075 acc: &'a mut usize,
3076 ) -> impl FnMut((), T) -> ControlFlow<usize, ()> + 'a {
3077 #[rustc_inherit_overflow_checks]
3078 move |_, x| {
3079 if predicate(x) {
3080 ControlFlow::Break(*acc)
3081 } else {
3082 *acc += 1;
3083 ControlFlow::Continue(())
3084 }
3085 }
3086 }
3087
3088 let mut acc = 0;
3089 self.try_fold((), check(predicate, &mut acc)).break_value()
3090 }
3091
3092 /// Searches for an element in an iterator from the right, returning its
3093 /// index.
3094 ///
3095 /// `rposition()` takes a closure that returns `true` or `false`. It applies
3096 /// this closure to each element of the iterator, starting from the end,
3097 /// and if one of them returns `true`, then `rposition()` returns
3098 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
3099 ///
3100 /// `rposition()` is short-circuiting; in other words, it will stop
3101 /// processing as soon as it finds a `true`.
3102 ///
3103 /// [`Some(index)`]: Some
3104 ///
3105 /// # Examples
3106 ///
3107 /// Basic usage:
3108 ///
3109 /// ```
3110 /// let a = [1, 2, 3];
3111 ///
3112 /// assert_eq!(a.into_iter().rposition(|x| x == 3), Some(2));
3113 ///
3114 /// assert_eq!(a.into_iter().rposition(|x| x == 5), None);
3115 /// ```
3116 ///
3117 /// Stopping at the first `true`:
3118 ///
3119 /// ```
3120 /// let a = [-1, 2, 3, 4];
3121 ///
3122 /// let mut iter = a.into_iter();
3123 ///
3124 /// assert_eq!(iter.rposition(|x| x >= 2), Some(3));
3125 ///
3126 /// // we can still use `iter`, as there are more elements.
3127 /// assert_eq!(iter.next(), Some(-1));
3128 /// assert_eq!(iter.next_back(), Some(3));
3129 /// ```
3130 #[inline]
3131 #[stable(feature = "rust1", since = "1.0.0")]
3132 fn rposition<P>(&mut self, predicate: P) -> Option<usize>
3133 where
3134 P: FnMut(Self::Item) -> bool,
3135 Self: Sized + ExactSizeIterator + DoubleEndedIterator,
3136 {
3137 // No need for an overflow check here, because `ExactSizeIterator`
3138 // implies that the number of elements fits into a `usize`.
3139 #[inline]
3140 fn check<T>(
3141 mut predicate: impl FnMut(T) -> bool,
3142 ) -> impl FnMut(usize, T) -> ControlFlow<usize, usize> {
3143 move |i, x| {
3144 let i = i - 1;
3145 if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i) }
3146 }
3147 }
3148
3149 let n = self.len();
3150 self.try_rfold(n, check(predicate)).break_value()
3151 }
3152
3153 /// Returns the maximum element of an iterator.
3154 ///
3155 /// If several elements are equally maximum, the last element is
3156 /// returned. If the iterator is empty, [`None`] is returned.
3157 ///
3158 /// Note that [`f32`]/[`f64`] doesn't implement [`Ord`] due to NaN being
3159 /// incomparable. You can work around this by using [`Iterator::reduce`]:
3160 /// ```
3161 /// assert_eq!(
3162 /// [2.4, f32::NAN, 1.3]
3163 /// .into_iter()
3164 /// .reduce(f32::max)
3165 /// .unwrap_or(0.),
3166 /// 2.4
3167 /// );
3168 /// ```
3169 ///
3170 /// # Examples
3171 ///
3172 /// ```
3173 /// let a = [1, 2, 3];
3174 /// let b: [u32; 0] = [];
3175 ///
3176 /// assert_eq!(a.into_iter().max(), Some(3));
3177 /// assert_eq!(b.into_iter().max(), None);
3178 /// ```
3179 #[inline]
3180 #[stable(feature = "rust1", since = "1.0.0")]
3181 fn max(self) -> Option<Self::Item>
3182 where
3183 Self: Sized,
3184 Self::Item: Ord,
3185 {
3186 self.max_by(Ord::cmp)
3187 }
3188
3189 /// Returns the minimum element of an iterator.
3190 ///
3191 /// If several elements are equally minimum, the first element is returned.
3192 /// If the iterator is empty, [`None`] is returned.
3193 ///
3194 /// Note that [`f32`]/[`f64`] doesn't implement [`Ord`] due to NaN being
3195 /// incomparable. You can work around this by using [`Iterator::reduce`]:
3196 /// ```
3197 /// assert_eq!(
3198 /// [2.4, f32::NAN, 1.3]
3199 /// .into_iter()
3200 /// .reduce(f32::min)
3201 /// .unwrap_or(0.),
3202 /// 1.3
3203 /// );
3204 /// ```
3205 ///
3206 /// # Examples
3207 ///
3208 /// ```
3209 /// let a = [1, 2, 3];
3210 /// let b: [u32; 0] = [];
3211 ///
3212 /// assert_eq!(a.into_iter().min(), Some(1));
3213 /// assert_eq!(b.into_iter().min(), None);
3214 /// ```
3215 #[inline]
3216 #[stable(feature = "rust1", since = "1.0.0")]
3217 fn min(self) -> Option<Self::Item>
3218 where
3219 Self: Sized,
3220 Self::Item: Ord,
3221 {
3222 self.min_by(Ord::cmp)
3223 }
3224
3225 /// Returns the element that gives the maximum value from the
3226 /// specified function.
3227 ///
3228 /// If several elements are equally maximum, the last element is
3229 /// returned. If the iterator is empty, [`None`] is returned.
3230 ///
3231 /// # Examples
3232 ///
3233 /// ```
3234 /// let a = [-3_i32, 0, 1, 5, -10];
3235 /// assert_eq!(a.into_iter().max_by_key(|x| x.abs()).unwrap(), -10);
3236 /// ```
3237 #[inline]
3238 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
3239 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
3240 where
3241 Self: Sized,
3242 F: FnMut(&Self::Item) -> B,
3243 {
3244 #[inline]
3245 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
3246 move |x| (f(&x), x)
3247 }
3248
3249 #[inline]
3250 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
3251 x_p.cmp(y_p)
3252 }
3253
3254 let (_, x) = self.map(key(f)).max_by(compare)?;
3255 Some(x)
3256 }
3257
3258 /// Returns the element that gives the maximum value with respect to the
3259 /// specified comparison function.
3260 ///
3261 /// If several elements are equally maximum, the last element is
3262 /// returned. If the iterator is empty, [`None`] is returned.
3263 ///
3264 /// # Examples
3265 ///
3266 /// ```
3267 /// let a = [-3_i32, 0, 1, 5, -10];
3268 /// assert_eq!(a.into_iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
3269 /// ```
3270 #[inline]
3271 #[stable(feature = "iter_max_by", since = "1.15.0")]
3272 fn max_by<F>(self, compare: F) -> Option<Self::Item>
3273 where
3274 Self: Sized,
3275 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
3276 {
3277 #[inline]
3278 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
3279 move |x, y| cmp::max_by(x, y, &mut compare)
3280 }
3281
3282 self.reduce(fold(compare))
3283 }
3284
3285 /// Returns the element that gives the minimum value from the
3286 /// specified function.
3287 ///
3288 /// If several elements are equally minimum, the first element is
3289 /// returned. If the iterator is empty, [`None`] is returned.
3290 ///
3291 /// # Examples
3292 ///
3293 /// ```
3294 /// let a = [-3_i32, 0, 1, 5, -10];
3295 /// assert_eq!(a.into_iter().min_by_key(|x| x.abs()).unwrap(), 0);
3296 /// ```
3297 #[inline]
3298 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
3299 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
3300 where
3301 Self: Sized,
3302 F: FnMut(&Self::Item) -> B,
3303 {
3304 #[inline]
3305 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
3306 move |x| (f(&x), x)
3307 }
3308
3309 #[inline]
3310 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
3311 x_p.cmp(y_p)
3312 }
3313
3314 let (_, x) = self.map(key(f)).min_by(compare)?;
3315 Some(x)
3316 }
3317
3318 /// Returns the element that gives the minimum value with respect to the
3319 /// specified comparison function.
3320 ///
3321 /// If several elements are equally minimum, the first element is
3322 /// returned. If the iterator is empty, [`None`] is returned.
3323 ///
3324 /// # Examples
3325 ///
3326 /// ```
3327 /// let a = [-3_i32, 0, 1, 5, -10];
3328 /// assert_eq!(a.into_iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
3329 /// ```
3330 #[inline]
3331 #[stable(feature = "iter_min_by", since = "1.15.0")]
3332 fn min_by<F>(self, compare: F) -> Option<Self::Item>
3333 where
3334 Self: Sized,
3335 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
3336 {
3337 #[inline]
3338 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
3339 move |x, y| cmp::min_by(x, y, &mut compare)
3340 }
3341
3342 self.reduce(fold(compare))
3343 }
3344
3345 /// Reverses an iterator's direction.
3346 ///
3347 /// Usually, iterators iterate from left to right. After using `rev()`,
3348 /// an iterator will instead iterate from right to left.
3349 ///
3350 /// This is only possible if the iterator has an end, so `rev()` only
3351 /// works on [`DoubleEndedIterator`]s.
3352 ///
3353 /// # Examples
3354 ///
3355 /// ```
3356 /// let a = [1, 2, 3];
3357 ///
3358 /// let mut iter = a.into_iter().rev();
3359 ///
3360 /// assert_eq!(iter.next(), Some(3));
3361 /// assert_eq!(iter.next(), Some(2));
3362 /// assert_eq!(iter.next(), Some(1));
3363 ///
3364 /// assert_eq!(iter.next(), None);
3365 /// ```
3366 #[inline]
3367 #[doc(alias = "reverse")]
3368 #[stable(feature = "rust1", since = "1.0.0")]
3369 fn rev(self) -> Rev<Self>
3370 where
3371 Self: Sized + DoubleEndedIterator,
3372 {
3373 Rev::new(self)
3374 }
3375
3376 /// Converts an iterator of pairs into a pair of containers.
3377 ///
3378 /// `unzip()` consumes an entire iterator of pairs, producing two
3379 /// collections: one from the left elements of the pairs, and one
3380 /// from the right elements.
3381 ///
3382 /// This function is, in some sense, the opposite of [`zip`].
3383 ///
3384 /// [`zip`]: Iterator::zip
3385 ///
3386 /// # Examples
3387 ///
3388 /// ```
3389 /// let a = [(1, 2), (3, 4), (5, 6)];
3390 ///
3391 /// let (left, right): (Vec<_>, Vec<_>) = a.into_iter().unzip();
3392 ///
3393 /// assert_eq!(left, [1, 3, 5]);
3394 /// assert_eq!(right, [2, 4, 6]);
3395 ///
3396 /// // you can also unzip multiple nested tuples at once
3397 /// let a = [(1, (2, 3)), (4, (5, 6))];
3398 ///
3399 /// let (x, (y, z)): (Vec<_>, (Vec<_>, Vec<_>)) = a.into_iter().unzip();
3400 /// assert_eq!(x, [1, 4]);
3401 /// assert_eq!(y, [2, 5]);
3402 /// assert_eq!(z, [3, 6]);
3403 /// ```
3404 #[stable(feature = "rust1", since = "1.0.0")]
3405 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
3406 where
3407 FromA: Default + Extend<A>,
3408 FromB: Default + Extend<B>,
3409 Self: Sized + Iterator<Item = (A, B)>,
3410 {
3411 let mut unzipped: (FromA, FromB) = Default::default();
3412 unzipped.extend(self);
3413 unzipped
3414 }
3415
3416 /// Creates an iterator which copies all of its elements.
3417 ///
3418 /// This is useful when you have an iterator over `&T`, but you need an
3419 /// iterator over `T`.
3420 ///
3421 /// # Examples
3422 ///
3423 /// ```
3424 /// let a = [1, 2, 3];
3425 ///
3426 /// let v_copied: Vec<_> = a.iter().copied().collect();
3427 ///
3428 /// // copied is the same as .map(|&x| x)
3429 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
3430 ///
3431 /// assert_eq!(v_copied, [1, 2, 3]);
3432 /// assert_eq!(v_map, [1, 2, 3]);
3433 /// ```
3434 #[stable(feature = "iter_copied", since = "1.36.0")]
3435 #[rustc_diagnostic_item = "iter_copied"]
3436 fn copied<'a, T>(self) -> Copied<Self>
3437 where
3438 T: Copy + 'a,
3439 Self: Sized + Iterator<Item = &'a T>,
3440 {
3441 Copied::new(self)
3442 }
3443
3444 /// Creates an iterator which [`clone`]s all of its elements.
3445 ///
3446 /// This is useful when you have an iterator over `&T`, but you need an
3447 /// iterator over `T`.
3448 ///
3449 /// There is no guarantee whatsoever about the `clone` method actually
3450 /// being called *or* optimized away. So code should not depend on
3451 /// either.
3452 ///
3453 /// [`clone`]: Clone::clone
3454 ///
3455 /// # Examples
3456 ///
3457 /// Basic usage:
3458 ///
3459 /// ```
3460 /// let a = [1, 2, 3];
3461 ///
3462 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
3463 ///
3464 /// // cloned is the same as .map(|&x| x), for integers
3465 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
3466 ///
3467 /// assert_eq!(v_cloned, [1, 2, 3]);
3468 /// assert_eq!(v_map, [1, 2, 3]);
3469 /// ```
3470 ///
3471 /// To get the best performance, try to clone late:
3472 ///
3473 /// ```
3474 /// let a = [vec![0_u8, 1, 2], vec![3, 4], vec![23]];
3475 /// // don't do this:
3476 /// let slower: Vec<_> = a.iter().cloned().filter(|s| s.len() == 1).collect();
3477 /// assert_eq!(&[vec![23]], &slower[..]);
3478 /// // instead call `cloned` late
3479 /// let faster: Vec<_> = a.iter().filter(|s| s.len() == 1).cloned().collect();
3480 /// assert_eq!(&[vec![23]], &faster[..]);
3481 /// ```
3482 #[stable(feature = "rust1", since = "1.0.0")]
3483 #[rustc_diagnostic_item = "iter_cloned"]
3484 fn cloned<'a, T>(self) -> Cloned<Self>
3485 where
3486 T: Clone + 'a,
3487 Self: Sized + Iterator<Item = &'a T>,
3488 {
3489 Cloned::new(self)
3490 }
3491
3492 /// Repeats an iterator endlessly.
3493 ///
3494 /// Instead of stopping at [`None`], the iterator will instead start again,
3495 /// from the beginning. After iterating again, it will start at the
3496 /// beginning again. And again. And again. Forever. Note that in case the
3497 /// original iterator is empty, the resulting iterator will also be empty.
3498 ///
3499 /// # Examples
3500 ///
3501 /// ```
3502 /// let a = [1, 2, 3];
3503 ///
3504 /// let mut iter = a.into_iter().cycle();
3505 ///
3506 /// loop {
3507 /// assert_eq!(iter.next(), Some(1));
3508 /// assert_eq!(iter.next(), Some(2));
3509 /// assert_eq!(iter.next(), Some(3));
3510 /// # break;
3511 /// }
3512 /// ```
3513 #[stable(feature = "rust1", since = "1.0.0")]
3514 #[inline]
3515 fn cycle(self) -> Cycle<Self>
3516 where
3517 Self: Sized + Clone,
3518 {
3519 Cycle::new(self)
3520 }
3521
3522 /// Returns an iterator over `N` elements of the iterator at a time.
3523 ///
3524 /// The chunks do not overlap. If `N` does not divide the length of the
3525 /// iterator, then the last up to `N-1` elements will be omitted and can be
3526 /// retrieved from the [`.into_remainder()`][ArrayChunks::into_remainder]
3527 /// function of the iterator.
3528 ///
3529 /// # Panics
3530 ///
3531 /// Panics if `N` is zero.
3532 ///
3533 /// # Examples
3534 ///
3535 /// Basic usage:
3536 ///
3537 /// ```
3538 /// #![feature(iter_array_chunks)]
3539 ///
3540 /// let mut iter = "lorem".chars().array_chunks();
3541 /// assert_eq!(iter.next(), Some(['l', 'o']));
3542 /// assert_eq!(iter.next(), Some(['r', 'e']));
3543 /// assert_eq!(iter.next(), None);
3544 /// assert_eq!(iter.into_remainder().as_slice(), &['m']);
3545 /// ```
3546 ///
3547 /// ```
3548 /// #![feature(iter_array_chunks)]
3549 ///
3550 /// let data = [1, 1, 2, -2, 6, 0, 3, 1];
3551 /// // ^-----^ ^------^
3552 /// for [x, y, z] in data.iter().array_chunks() {
3553 /// assert_eq!(x + y + z, 4);
3554 /// }
3555 /// ```
3556 #[track_caller]
3557 #[unstable(feature = "iter_array_chunks", reason = "recently added", issue = "100450")]
3558 fn array_chunks<const N: usize>(self) -> ArrayChunks<Self, N>
3559 where
3560 Self: Sized,
3561 {
3562 ArrayChunks::new(self)
3563 }
3564
3565 /// Sums the elements of an iterator.
3566 ///
3567 /// Takes each element, adds them together, and returns the result.
3568 ///
3569 /// An empty iterator returns the *additive identity* ("zero") of the type,
3570 /// which is `0` for integers and `-0.0` for floats.
3571 ///
3572 /// `sum()` can be used to sum any type implementing [`Sum`][`core::iter::Sum`],
3573 /// including [`Option`][`Option::sum`] and [`Result`][`Result::sum`].
3574 ///
3575 /// # Panics
3576 ///
3577 /// When calling `sum()` and a primitive integer type is being returned, this
3578 /// method will panic if the computation overflows and overflow checks are
3579 /// enabled.
3580 ///
3581 /// # Examples
3582 ///
3583 /// ```
3584 /// let a = [1, 2, 3];
3585 /// let sum: i32 = a.iter().sum();
3586 ///
3587 /// assert_eq!(sum, 6);
3588 ///
3589 /// let b: Vec<f32> = vec![];
3590 /// let sum: f32 = b.iter().sum();
3591 /// assert_eq!(sum, -0.0_f32);
3592 /// ```
3593 #[stable(feature = "iter_arith", since = "1.11.0")]
3594 fn sum<S>(self) -> S
3595 where
3596 Self: Sized,
3597 S: Sum<Self::Item>,
3598 {
3599 Sum::sum(self)
3600 }
3601
3602 /// Iterates over the entire iterator, multiplying all the elements
3603 ///
3604 /// An empty iterator returns the one value of the type.
3605 ///
3606 /// `product()` can be used to multiply any type implementing [`Product`][`core::iter::Product`],
3607 /// including [`Option`][`Option::product`] and [`Result`][`Result::product`].
3608 ///
3609 /// # Panics
3610 ///
3611 /// When calling `product()` and a primitive integer type is being returned,
3612 /// method will panic if the computation overflows and overflow checks are
3613 /// enabled.
3614 ///
3615 /// # Examples
3616 ///
3617 /// ```
3618 /// fn factorial(n: u32) -> u32 {
3619 /// (1..=n).product()
3620 /// }
3621 /// assert_eq!(factorial(0), 1);
3622 /// assert_eq!(factorial(1), 1);
3623 /// assert_eq!(factorial(5), 120);
3624 /// ```
3625 #[stable(feature = "iter_arith", since = "1.11.0")]
3626 fn product<P>(self) -> P
3627 where
3628 Self: Sized,
3629 P: Product<Self::Item>,
3630 {
3631 Product::product(self)
3632 }
3633
3634 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3635 /// of another.
3636 ///
3637 /// # Examples
3638 ///
3639 /// ```
3640 /// use std::cmp::Ordering;
3641 ///
3642 /// assert_eq!([1].iter().cmp([1].iter()), Ordering::Equal);
3643 /// assert_eq!([1].iter().cmp([1, 2].iter()), Ordering::Less);
3644 /// assert_eq!([1, 2].iter().cmp([1].iter()), Ordering::Greater);
3645 /// ```
3646 #[stable(feature = "iter_order", since = "1.5.0")]
3647 fn cmp<I>(self, other: I) -> Ordering
3648 where
3649 I: IntoIterator<Item = Self::Item>,
3650 Self::Item: Ord,
3651 Self: Sized,
3652 {
3653 self.cmp_by(other, |x, y| x.cmp(&y))
3654 }
3655
3656 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3657 /// of another with respect to the specified comparison function.
3658 ///
3659 /// # Examples
3660 ///
3661 /// ```
3662 /// #![feature(iter_order_by)]
3663 ///
3664 /// use std::cmp::Ordering;
3665 ///
3666 /// let xs = [1, 2, 3, 4];
3667 /// let ys = [1, 4, 9, 16];
3668 ///
3669 /// assert_eq!(xs.into_iter().cmp_by(ys, |x, y| x.cmp(&y)), Ordering::Less);
3670 /// assert_eq!(xs.into_iter().cmp_by(ys, |x, y| (x * x).cmp(&y)), Ordering::Equal);
3671 /// assert_eq!(xs.into_iter().cmp_by(ys, |x, y| (2 * x).cmp(&y)), Ordering::Greater);
3672 /// ```
3673 #[unstable(feature = "iter_order_by", issue = "64295")]
3674 fn cmp_by<I, F>(self, other: I, cmp: F) -> Ordering
3675 where
3676 Self: Sized,
3677 I: IntoIterator,
3678 F: FnMut(Self::Item, I::Item) -> Ordering,
3679 {
3680 #[inline]
3681 fn compare<X, Y, F>(mut cmp: F) -> impl FnMut(X, Y) -> ControlFlow<Ordering>
3682 where
3683 F: FnMut(X, Y) -> Ordering,
3684 {
3685 move |x, y| match cmp(x, y) {
3686 Ordering::Equal => ControlFlow::Continue(()),
3687 non_eq => ControlFlow::Break(non_eq),
3688 }
3689 }
3690
3691 match iter_compare(self, other.into_iter(), compare(cmp)) {
3692 ControlFlow::Continue(ord) => ord,
3693 ControlFlow::Break(ord) => ord,
3694 }
3695 }
3696
3697 /// [Lexicographically](Ord#lexicographical-comparison) compares the [`PartialOrd`] elements of
3698 /// this [`Iterator`] with those of another. The comparison works like short-circuit
3699 /// evaluation, returning a result without comparing the remaining elements.
3700 /// As soon as an order can be determined, the evaluation stops and a result is returned.
3701 ///
3702 /// # Examples
3703 ///
3704 /// ```
3705 /// use std::cmp::Ordering;
3706 ///
3707 /// assert_eq!([1.].iter().partial_cmp([1.].iter()), Some(Ordering::Equal));
3708 /// assert_eq!([1.].iter().partial_cmp([1., 2.].iter()), Some(Ordering::Less));
3709 /// assert_eq!([1., 2.].iter().partial_cmp([1.].iter()), Some(Ordering::Greater));
3710 /// ```
3711 ///
3712 /// For floating-point numbers, NaN does not have a total order and will result
3713 /// in `None` when compared:
3714 ///
3715 /// ```
3716 /// assert_eq!([f64::NAN].iter().partial_cmp([1.].iter()), None);
3717 /// ```
3718 ///
3719 /// The results are determined by the order of evaluation.
3720 ///
3721 /// ```
3722 /// use std::cmp::Ordering;
3723 ///
3724 /// assert_eq!([1.0, f64::NAN].iter().partial_cmp([2.0, f64::NAN].iter()), Some(Ordering::Less));
3725 /// assert_eq!([2.0, f64::NAN].iter().partial_cmp([1.0, f64::NAN].iter()), Some(Ordering::Greater));
3726 /// assert_eq!([f64::NAN, 1.0].iter().partial_cmp([f64::NAN, 2.0].iter()), None);
3727 /// ```
3728 ///
3729 #[stable(feature = "iter_order", since = "1.5.0")]
3730 fn partial_cmp<I>(self, other: I) -> Option<Ordering>
3731 where
3732 I: IntoIterator,
3733 Self::Item: PartialOrd<I::Item>,
3734 Self: Sized,
3735 {
3736 self.partial_cmp_by(other, |x, y| x.partial_cmp(&y))
3737 }
3738
3739 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3740 /// of another with respect to the specified comparison function.
3741 ///
3742 /// # Examples
3743 ///
3744 /// ```
3745 /// #![feature(iter_order_by)]
3746 ///
3747 /// use std::cmp::Ordering;
3748 ///
3749 /// let xs = [1.0, 2.0, 3.0, 4.0];
3750 /// let ys = [1.0, 4.0, 9.0, 16.0];
3751 ///
3752 /// assert_eq!(
3753 /// xs.iter().partial_cmp_by(ys, |x, y| x.partial_cmp(&y)),
3754 /// Some(Ordering::Less)
3755 /// );
3756 /// assert_eq!(
3757 /// xs.iter().partial_cmp_by(ys, |x, y| (x * x).partial_cmp(&y)),
3758 /// Some(Ordering::Equal)
3759 /// );
3760 /// assert_eq!(
3761 /// xs.iter().partial_cmp_by(ys, |x, y| (2.0 * x).partial_cmp(&y)),
3762 /// Some(Ordering::Greater)
3763 /// );
3764 /// ```
3765 #[unstable(feature = "iter_order_by", issue = "64295")]
3766 fn partial_cmp_by<I, F>(self, other: I, partial_cmp: F) -> Option<Ordering>
3767 where
3768 Self: Sized,
3769 I: IntoIterator,
3770 F: FnMut(Self::Item, I::Item) -> Option<Ordering>,
3771 {
3772 #[inline]
3773 fn compare<X, Y, F>(mut partial_cmp: F) -> impl FnMut(X, Y) -> ControlFlow<Option<Ordering>>
3774 where
3775 F: FnMut(X, Y) -> Option<Ordering>,
3776 {
3777 move |x, y| match partial_cmp(x, y) {
3778 Some(Ordering::Equal) => ControlFlow::Continue(()),
3779 non_eq => ControlFlow::Break(non_eq),
3780 }
3781 }
3782
3783 match iter_compare(self, other.into_iter(), compare(partial_cmp)) {
3784 ControlFlow::Continue(ord) => Some(ord),
3785 ControlFlow::Break(ord) => ord,
3786 }
3787 }
3788
3789 /// Determines if the elements of this [`Iterator`] are equal to those of
3790 /// another.
3791 ///
3792 /// # Examples
3793 ///
3794 /// ```
3795 /// assert_eq!([1].iter().eq([1].iter()), true);
3796 /// assert_eq!([1].iter().eq([1, 2].iter()), false);
3797 /// ```
3798 #[stable(feature = "iter_order", since = "1.5.0")]
3799 fn eq<I>(self, other: I) -> bool
3800 where
3801 I: IntoIterator,
3802 Self::Item: PartialEq<I::Item>,
3803 Self: Sized,
3804 {
3805 self.eq_by(other, |x, y| x == y)
3806 }
3807
3808 /// Determines if the elements of this [`Iterator`] are equal to those of
3809 /// another with respect to the specified equality function.
3810 ///
3811 /// # Examples
3812 ///
3813 /// ```
3814 /// #![feature(iter_order_by)]
3815 ///
3816 /// let xs = [1, 2, 3, 4];
3817 /// let ys = [1, 4, 9, 16];
3818 ///
3819 /// assert!(xs.iter().eq_by(ys, |x, y| x * x == y));
3820 /// ```
3821 #[unstable(feature = "iter_order_by", issue = "64295")]
3822 fn eq_by<I, F>(self, other: I, eq: F) -> bool
3823 where
3824 Self: Sized,
3825 I: IntoIterator,
3826 F: FnMut(Self::Item, I::Item) -> bool,
3827 {
3828 #[inline]
3829 fn compare<X, Y, F>(mut eq: F) -> impl FnMut(X, Y) -> ControlFlow<()>
3830 where
3831 F: FnMut(X, Y) -> bool,
3832 {
3833 move |x, y| {
3834 if eq(x, y) { ControlFlow::Continue(()) } else { ControlFlow::Break(()) }
3835 }
3836 }
3837
3838 SpecIterEq::spec_iter_eq(self, other.into_iter(), compare(eq))
3839 }
3840
3841 /// Determines if the elements of this [`Iterator`] are not equal to those of
3842 /// another.
3843 ///
3844 /// # Examples
3845 ///
3846 /// ```
3847 /// assert_eq!([1].iter().ne([1].iter()), false);
3848 /// assert_eq!([1].iter().ne([1, 2].iter()), true);
3849 /// ```
3850 #[stable(feature = "iter_order", since = "1.5.0")]
3851 fn ne<I>(self, other: I) -> bool
3852 where
3853 I: IntoIterator,
3854 Self::Item: PartialEq<I::Item>,
3855 Self: Sized,
3856 {
3857 !self.eq(other)
3858 }
3859
3860 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3861 /// less than those of another.
3862 ///
3863 /// # Examples
3864 ///
3865 /// ```
3866 /// assert_eq!([1].iter().lt([1].iter()), false);
3867 /// assert_eq!([1].iter().lt([1, 2].iter()), true);
3868 /// assert_eq!([1, 2].iter().lt([1].iter()), false);
3869 /// assert_eq!([1, 2].iter().lt([1, 2].iter()), false);
3870 /// ```
3871 #[stable(feature = "iter_order", since = "1.5.0")]
3872 fn lt<I>(self, other: I) -> bool
3873 where
3874 I: IntoIterator,
3875 Self::Item: PartialOrd<I::Item>,
3876 Self: Sized,
3877 {
3878 self.partial_cmp(other) == Some(Ordering::Less)
3879 }
3880
3881 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3882 /// less or equal to those of another.
3883 ///
3884 /// # Examples
3885 ///
3886 /// ```
3887 /// assert_eq!([1].iter().le([1].iter()), true);
3888 /// assert_eq!([1].iter().le([1, 2].iter()), true);
3889 /// assert_eq!([1, 2].iter().le([1].iter()), false);
3890 /// assert_eq!([1, 2].iter().le([1, 2].iter()), true);
3891 /// ```
3892 #[stable(feature = "iter_order", since = "1.5.0")]
3893 fn le<I>(self, other: I) -> bool
3894 where
3895 I: IntoIterator,
3896 Self::Item: PartialOrd<I::Item>,
3897 Self: Sized,
3898 {
3899 matches!(self.partial_cmp(other), Some(Ordering::Less | Ordering::Equal))
3900 }
3901
3902 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3903 /// greater than those of another.
3904 ///
3905 /// # Examples
3906 ///
3907 /// ```
3908 /// assert_eq!([1].iter().gt([1].iter()), false);
3909 /// assert_eq!([1].iter().gt([1, 2].iter()), false);
3910 /// assert_eq!([1, 2].iter().gt([1].iter()), true);
3911 /// assert_eq!([1, 2].iter().gt([1, 2].iter()), false);
3912 /// ```
3913 #[stable(feature = "iter_order", since = "1.5.0")]
3914 fn gt<I>(self, other: I) -> bool
3915 where
3916 I: IntoIterator,
3917 Self::Item: PartialOrd<I::Item>,
3918 Self: Sized,
3919 {
3920 self.partial_cmp(other) == Some(Ordering::Greater)
3921 }
3922
3923 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3924 /// greater than or equal to those of another.
3925 ///
3926 /// # Examples
3927 ///
3928 /// ```
3929 /// assert_eq!([1].iter().ge([1].iter()), true);
3930 /// assert_eq!([1].iter().ge([1, 2].iter()), false);
3931 /// assert_eq!([1, 2].iter().ge([1].iter()), true);
3932 /// assert_eq!([1, 2].iter().ge([1, 2].iter()), true);
3933 /// ```
3934 #[stable(feature = "iter_order", since = "1.5.0")]
3935 fn ge<I>(self, other: I) -> bool
3936 where
3937 I: IntoIterator,
3938 Self::Item: PartialOrd<I::Item>,
3939 Self: Sized,
3940 {
3941 matches!(self.partial_cmp(other), Some(Ordering::Greater | Ordering::Equal))
3942 }
3943
3944 /// Checks if the elements of this iterator are sorted.
3945 ///
3946 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
3947 /// iterator yields exactly zero or one element, `true` is returned.
3948 ///
3949 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
3950 /// implies that this function returns `false` if any two consecutive items are not
3951 /// comparable.
3952 ///
3953 /// # Examples
3954 ///
3955 /// ```
3956 /// assert!([1, 2, 2, 9].iter().is_sorted());
3957 /// assert!(![1, 3, 2, 4].iter().is_sorted());
3958 /// assert!([0].iter().is_sorted());
3959 /// assert!(std::iter::empty::<i32>().is_sorted());
3960 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted());
3961 /// ```
3962 #[inline]
3963 #[stable(feature = "is_sorted", since = "1.82.0")]
3964 fn is_sorted(self) -> bool
3965 where
3966 Self: Sized,
3967 Self::Item: PartialOrd,
3968 {
3969 self.is_sorted_by(|a, b| a <= b)
3970 }
3971
3972 /// Checks if the elements of this iterator are sorted using the given comparator function.
3973 ///
3974 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
3975 /// function to determine whether two elements are to be considered in sorted order.
3976 ///
3977 /// # Examples
3978 ///
3979 /// ```
3980 /// assert!([1, 2, 2, 9].iter().is_sorted_by(|a, b| a <= b));
3981 /// assert!(![1, 2, 2, 9].iter().is_sorted_by(|a, b| a < b));
3982 ///
3983 /// assert!([0].iter().is_sorted_by(|a, b| true));
3984 /// assert!([0].iter().is_sorted_by(|a, b| false));
3985 ///
3986 /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| false));
3987 /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| true));
3988 /// ```
3989 #[stable(feature = "is_sorted", since = "1.82.0")]
3990 fn is_sorted_by<F>(mut self, compare: F) -> bool
3991 where
3992 Self: Sized,
3993 F: FnMut(&Self::Item, &Self::Item) -> bool,
3994 {
3995 #[inline]
3996 fn check<'a, T>(
3997 last: &'a mut T,
3998 mut compare: impl FnMut(&T, &T) -> bool + 'a,
3999 ) -> impl FnMut(T) -> bool + 'a {
4000 move |curr| {
4001 if !compare(&last, &curr) {
4002 return false;
4003 }
4004 *last = curr;
4005 true
4006 }
4007 }
4008
4009 let mut last = match self.next() {
4010 Some(e) => e,
4011 None => return true,
4012 };
4013
4014 self.all(check(&mut last, compare))
4015 }
4016
4017 /// Checks if the elements of this iterator are sorted using the given key extraction
4018 /// function.
4019 ///
4020 /// Instead of comparing the iterator's elements directly, this function compares the keys of
4021 /// the elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see
4022 /// its documentation for more information.
4023 ///
4024 /// [`is_sorted`]: Iterator::is_sorted
4025 ///
4026 /// # Examples
4027 ///
4028 /// ```
4029 /// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len()));
4030 /// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
4031 /// ```
4032 #[inline]
4033 #[stable(feature = "is_sorted", since = "1.82.0")]
4034 fn is_sorted_by_key<F, K>(self, f: F) -> bool
4035 where
4036 Self: Sized,
4037 F: FnMut(Self::Item) -> K,
4038 K: PartialOrd,
4039 {
4040 self.map(f).is_sorted()
4041 }
4042
4043 /// See [TrustedRandomAccess][super::super::TrustedRandomAccess]
4044 // The unusual name is to avoid name collisions in method resolution
4045 // see #76479.
4046 #[inline]
4047 #[doc(hidden)]
4048 #[unstable(feature = "trusted_random_access", issue = "none")]
4049 unsafe fn __iterator_get_unchecked(&mut self, _idx: usize) -> Self::Item
4050 where
4051 Self: TrustedRandomAccessNoCoerce,
4052 {
4053 unreachable!("Always specialized");
4054 }
4055}
4056
4057trait SpecIterEq<B: Iterator>: Iterator {
4058 fn spec_iter_eq<F>(self, b: B, f: F) -> bool
4059 where
4060 F: FnMut(Self::Item, <B as Iterator>::Item) -> ControlFlow<()>;
4061}
4062
4063impl<A: Iterator, B: Iterator> SpecIterEq<B> for A {
4064 #[inline]
4065 default fn spec_iter_eq<F>(self, b: B, f: F) -> bool
4066 where
4067 F: FnMut(Self::Item, <B as Iterator>::Item) -> ControlFlow<()>,
4068 {
4069 iter_eq(self, b, f)
4070 }
4071}
4072
4073impl<A: Iterator + TrustedLen, B: Iterator + TrustedLen> SpecIterEq<B> for A {
4074 #[inline]
4075 fn spec_iter_eq<F>(self, b: B, f: F) -> bool
4076 where
4077 F: FnMut(Self::Item, <B as Iterator>::Item) -> ControlFlow<()>,
4078 {
4079 // we *can't* short-circuit if:
4080 match (self.size_hint(), b.size_hint()) {
4081 // ... both iterators have the same length
4082 ((_, Some(a)), (_, Some(b))) if a == b => {}
4083 // ... or both of them are longer than `usize::MAX` (i.e. have an unknown length).
4084 ((_, None), (_, None)) => {}
4085 // otherwise, we can ascertain that they are unequal without actually comparing items
4086 _ => return false,
4087 }
4088
4089 iter_eq(self, b, f)
4090 }
4091}
4092
4093/// Compares two iterators element-wise using the given function.
4094///
4095/// If `ControlFlow::Continue(())` is returned from the function, the comparison moves on to the next
4096/// elements of both iterators. Returning `ControlFlow::Break(x)` short-circuits the iteration and
4097/// returns `ControlFlow::Break(x)`. If one of the iterators runs out of elements,
4098/// `ControlFlow::Continue(ord)` is returned where `ord` is the result of comparing the lengths of
4099/// the iterators.
4100///
4101/// Isolates the logic shared by ['cmp_by'](Iterator::cmp_by),
4102/// ['partial_cmp_by'](Iterator::partial_cmp_by), and ['eq_by'](Iterator::eq_by).
4103#[inline]
4104fn iter_compare<A, B, F, T>(mut a: A, mut b: B, f: F) -> ControlFlow<T, Ordering>
4105where
4106 A: Iterator,
4107 B: Iterator,
4108 F: FnMut(A::Item, B::Item) -> ControlFlow<T>,
4109{
4110 #[inline]
4111 fn compare<'a, B, X, T>(
4112 b: &'a mut B,
4113 mut f: impl FnMut(X, B::Item) -> ControlFlow<T> + 'a,
4114 ) -> impl FnMut(X) -> ControlFlow<ControlFlow<T, Ordering>> + 'a
4115 where
4116 B: Iterator,
4117 {
4118 move |x| match b.next() {
4119 None => ControlFlow::Break(ControlFlow::Continue(Ordering::Greater)),
4120 Some(y) => f(x, y).map_break(ControlFlow::Break),
4121 }
4122 }
4123
4124 match a.try_for_each(compare(&mut b, f)) {
4125 ControlFlow::Continue(()) => ControlFlow::Continue(match b.next() {
4126 None => Ordering::Equal,
4127 Some(_) => Ordering::Less,
4128 }),
4129 ControlFlow::Break(x) => x,
4130 }
4131}
4132
4133#[inline]
4134fn iter_eq<A, B, F>(a: A, b: B, f: F) -> bool
4135where
4136 A: Iterator,
4137 B: Iterator,
4138 F: FnMut(A::Item, B::Item) -> ControlFlow<()>,
4139{
4140 iter_compare(a, b, f).continue_value().is_some_and(|ord| ord == Ordering::Equal)
4141}
4142
4143/// Implements `Iterator` for mutable references to iterators, such as those produced by [`Iterator::by_ref`].
4144///
4145/// This implementation passes all method calls on to the original iterator.
4146#[stable(feature = "rust1", since = "1.0.0")]
4147impl<I: Iterator + ?Sized> Iterator for &mut I {
4148 type Item = I::Item;
4149 #[inline]
4150 fn next(&mut self) -> Option<I::Item> {
4151 (**self).next()
4152 }
4153 fn size_hint(&self) -> (usize, Option<usize>) {
4154 (**self).size_hint()
4155 }
4156 fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
4157 (**self).advance_by(n)
4158 }
4159 fn nth(&mut self, n: usize) -> Option<Self::Item> {
4160 (**self).nth(n)
4161 }
4162 fn fold<B, F>(self, init: B, f: F) -> B
4163 where
4164 F: FnMut(B, Self::Item) -> B,
4165 {
4166 self.spec_fold(init, f)
4167 }
4168 fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
4169 where
4170 F: FnMut(B, Self::Item) -> R,
4171 R: Try<Output = B>,
4172 {
4173 self.spec_try_fold(init, f)
4174 }
4175}
4176
4177/// Helper trait to specialize `fold` and `try_fold` for `&mut I where I: Sized`
4178trait IteratorRefSpec: Iterator {
4179 fn spec_fold<B, F>(self, init: B, f: F) -> B
4180 where
4181 F: FnMut(B, Self::Item) -> B;
4182
4183 fn spec_try_fold<B, F, R>(&mut self, init: B, f: F) -> R
4184 where
4185 F: FnMut(B, Self::Item) -> R,
4186 R: Try<Output = B>;
4187}
4188
4189impl<I: Iterator + ?Sized> IteratorRefSpec for &mut I {
4190 default fn spec_fold<B, F>(self, init: B, mut f: F) -> B
4191 where
4192 F: FnMut(B, Self::Item) -> B,
4193 {
4194 let mut accum = init;
4195 while let Some(x) = self.next() {
4196 accum = f(accum, x);
4197 }
4198 accum
4199 }
4200
4201 default fn spec_try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
4202 where
4203 F: FnMut(B, Self::Item) -> R,
4204 R: Try<Output = B>,
4205 {
4206 let mut accum = init;
4207 while let Some(x) = self.next() {
4208 accum = f(accum, x)?;
4209 }
4210 try { accum }
4211 }
4212}
4213
4214impl<I: Iterator> IteratorRefSpec for &mut I {
4215 impl_fold_via_try_fold! { spec_fold -> spec_try_fold }
4216
4217 fn spec_try_fold<B, F, R>(&mut self, init: B, f: F) -> R
4218 where
4219 F: FnMut(B, Self::Item) -> R,
4220 R: Try<Output = B>,
4221 {
4222 (**self).try_fold(init, f)
4223 }
4224}